FormView ItemUpdating e.oldValues and e.NewValues seems null - asp.net

I have a FormView on a page in my asp.net 4.5 VB application. I have a FileUpload in EditItemTemplate and InsertItemTemplate of my FormView. InsertItemTemplate works fine as expected. I want my FormView to:
Insert values into SQL DB, and save the file into the file system and save its name into DB (Which it does as expected).
Update DB and the file system by replacing the old values and with new ones (this is OK too.) and previous file of the row with the new file (This is OK too) and Delete the old file... (NOT OK!)
Keep the previous file name in DB if FileUpload has no file.(NOT OK!) records NULL if is empty.
Delete record from db along with the file associated (This is OK too.)
FormView:
<asp:FormView ID="FormView1" runat="server" AllowPaging="True" DataKeyNames="KurumId" DataSourceID="KurumlarDS" Width="500px">
<EditItemTemplate>
KurumId:
<asp:Label ID="KurumIdLabel1" runat="server" Text='<%# Eval("KurumId") %>' />
<br />
KurumAdi:
<asp:TextBox ID="KurumAdiTextBox" CssClass="form-control" runat="server" Text='<%# Bind("KurumAdi") %>' />
<br />
KurumLogoPath:
<%--<img runat="server" ID="imgKurumLogo" src='<%# Eval("KurumLogoPath", "../images/kurum/{0}?w=80")%>' alt="Kurum Logosu" />
<br />--%>
<asp:FileUpload ID="KurumLogoPathFUU" runat="server" />
<br />
KurumTelefon:
<asp:TextBox ID="KurumTelefonTextBox" CssClass="form-control" runat="server" Text='<%# Bind("KurumTelefon") %>' />
<br />
KurumBelgeGecer:
<asp:TextBox ID="KurumBelgeGecerTextBox" CssClass="form-control" runat="server" Text='<%# Bind("KurumBelgeGecer") %>' />
<br />
KurumWebAdresi:
<asp:TextBox ID="KurumWebAdresiTextBox" CssClass="form-control" runat="server" Text='<%# Bind("KurumWebAdresi") %>' />
<br />
KurumEMail:
<asp:TextBox ID="KurumEMailTextBox" CssClass="form-control" runat="server" Text='<%# Bind("KurumEMail") %>' />
<br />
KurumTarihce:
<asp:TextBox ID="KurumTarihceTextBox" CssClass="form-control" runat="server" Text='<%# Bind("KurumTarihce") %>' />
<br />
KurumRengi:
<asp:TextBox ID="KurumRengiTextBox" CssClass="form-control" runat="server" Text='<%# Bind("KurumRengi") %>' />
<br />
KurumAdres:
<asp:TextBox ID="KurumAdresTextBox" CssClass="form-control" runat="server" Text='<%# Bind("KurumAdres") %>' TextMode="MultiLine" />
<br />
KurumSortExpression:
<asp:TextBox ID="KurumSortExpressionTextBox" CssClass="form-control" runat="server" Text='<%# Bind("KurumSortExpression") %>' />
<br />
KurumLat:
<asp:TextBox ID="KurumLatTextBox" CssClass="form-control" runat="server" Text='<%# Bind("KurumLat") %>' />
<br />
KurumLon:
<asp:TextBox ID="KurumLonTextBox" CssClass="form-control" runat="server" Text='<%# Bind("KurumLon") %>' />
<br />
<asp:LinkButton ID="UpdateButton" runat="server" CausesValidation="True" CommandName="Update" Text="Güncelle" />
<asp:LinkButton ID="UpdateCancelButton" runat="server" CausesValidation="False" CommandName="Cancel" Text="Vazgeç" />
</EditItemTemplate>
<InsertItemTemplate>
</InsertItemTemplate>
<ItemTemplate>
</ItemTemplate>
<PagerSettings Mode="NumericFirstLast" Position="TopAndBottom" />
Related CodeBehind:
Private Sub FormView1_ItemUpdating(sender As Object, e As FormViewUpdateEventArgs) Handles FormView1.ItemUpdating
Dim fu As FileUpload = CType(FormView1.FindControl("KurumLogoPathFUU"), FileUpload)
Dim MyPath As String = Server.MapPath("~/images/kurum/")
Dim fName As String = fu.FileName
Dim FullPathedFile As String = MyPath & fName
Try
If fu.HasFile = True Then
Dim oldName As String = e.OldValues("KurumLogoPath")
Dim newName As String = e.NewValues("KurumLogoPath")
If File.Exists(MyPath & oldName) Then
File.Delete(MyPath & oldName)
End If
e.NewValues("KurumLogoPath") = fName
fu.SaveAs(FullPathedFile)
Else
e.NewValues("KurumLogoPath") = e.OldValues("KurumLogoPath")
End If
Catch ex As Exception
Response.Write("Cannot Update!" & ex.Message())
e.Cancel = True
End Try
End Sub
I can see MyPath but not e.NewValues("KurumLogoPath") or e.OldValues("KurumLogoPath") I also tried e.NewValues.Item("KurumLogoPath") and e.NewValues.Item("KurumLogoPath") with no success. So I think that all e.OldValues and e.NewValues are null.. Thus file.delete tries to delete C:\inetpub\wwwroot\WebApp1\images\kurum instead of C:\inetpub\wwwroot\WebApp1\images\kurum\oldfile.jpg as a result deletes nothing.
I have checked permissions for the folder and Application, they are OK. I have googled, binged, yahooed, trialed & errored with no success. It's been about two days now that I am on this :(
What am I doing wrong? Any ideas?
Thanks in advance.

After causita's comment I used index for the values. It worked for all columns except for KurumLogoPath column. While trying to find that columns index I realized that no index number was related to KurumLogoPath column. Then I realized indices are coming from <%# Bind("ColumName") %> statements.. But FileUpload control doesn't have databinding in it's nature just like a textbox or a hiddenfield did. So I added a hiddenfield under it:
<asp:FileUpload ID="KurumLogoPathFUU" runat="server" />
<asp:HiddenField ID="KurumLogoPathHF" Value='<%# Bind("KurumLogoPath") %>' runat="server" />
and then both e.OldValues("KurumLogoPath") and e.OldValues(2) and file deleting process worked very well.

Related

Unable to get TextBox text in DataList

I have a textbox in a datalist I'm trying to access in edit mode:
<asp:DataList ID="dl1" OnEditCommand="dl1_EditCommand"
OnCancelCommand="dl1_CancelCommand" OnUpdateCommand="dl1_UpdateCommand"
runat="server">
...
<asp:TextBox ID="tbType" Width="600" runat="server" Text='<%# Eval("Type") %>' />
CodeBehind:
protected void dl1_UpdateCommand(object sender, DataListCommandEventArgs e)
{
TextBox tb = (TextBox)e.Item.FindControl("tbType");
}
My code executes, but the value of the textbox is always empty, even though I have a value in it! I don't get either my updated text or the default text - I get a null. It finds the textbox, I've even opened the inspector to view its text...
This hasn't happened before and I'm not sure what I'm doing wrong. I've never had a problem like this before...
Full disclosure - this is a datalist inside a usercontrol.
UPDATE
Showing EditItemTemplate tags as requested.
The value is "" - I get a reference to the textbox, but no value.
<EditItemTemplate>
<td><asp:LinkButton ID="lbEdit" runat="server" Text="Update" CommandName="update" CausesValidation="false" />
<br /><asp:LinkButton ID="lbCancel" runat="server" Text="Cancel" CommandName="cancel" CausesValidation="false" />
</td>
<td>
<asp:HiddenField ID="hfID" runat="server" Value='<%# Eval("Id") %>' />
<asp:TextBox ID="tbType" Width="600" runat="server" Text='<%# Eval("Type") %>' />
</td>
<td></td>
</EditItemTemplate>

Calling a RequiredFieldValidator and ValidatorCallExtender inside GridView

I have a GridView with its columns being TextBoxes and after user made modifications to data within GridView I have a "Commit" Button thats located outside the GridView and also located under a different Content within the page... How do I set the Validator to work even though I have the validator set correctly but when I click on the "Commit" button it doesn't check for the validation and I believe its because the button is not inside the GridView or UpdatePanel... Is there a way to get around that? or A better approach?
Thanks for your help in advance.
Please select a Test from the dropdown below.<br />
<asp:DropDownList ID="ddlResult" runat="server"
onselectedindexchanged="ddlResult_SelectedIndexChanged"
AutoPostBack="True" CausesValidation="false">
</asp:DropDownList>
<br />
<asp:UpdatePanel ID="upGrid" runat="server">
<ContentTemplate>
<asp:GridView ID="grdResults" runat="server"
CssClass="gridview"
RowStyle-CssClass="gridview_itm"
AlternatingRowStyle-CssClass="gridview_aitm"
HeaderStyle-CssClass="gridview_hdr"
Width="100%" AutoGenerateColumns="False">
<Columns>
<asp:TemplateField HeaderText="Test">
<ItemTemplate>
<asp:Label ID="lblTest" runat="server" Text='<%#Eval("Test")%>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Result">
<ItemTemplate>
<asp:TextBox ID="tbResult" runat="server" Text='<%#Request.QueryString["t_ID"] == null ? null : Eval("n_Result") %>'></asp:TextBox>
<asp:Label ID="lblResult" runat="server" Text='<%#Eval("Validate")%>' ForeColor="#D50000"></asp:Label>
<asp:FilteredTextBoxExtender ID="ftbe" runat="server" TargetControlID="tbResult" FilterType="Custom, Numbers" ValidChars='<%#Eval("n_Mask")%>' />
<asp:RequiredFieldValidator runat="server" ID="RReq"
ControlToValidate="tbResult"
Display="None"
ErrorMessage="A Result is required." />
<asp:ValidatorCalloutExtender runat="Server" ID="RReqE"
TargetControlID="RReq"
HighlightCssClass="validatorCalloutHighlight" />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Date Completed">
<ItemTemplate>
<asp:TextBox ID="tbDate" runat="server" Text='<%#Request.QueryString["t_ID"] == null ? null : Eval("d_DateCompleted") %>'></asp:TextBox>
<asp:Image ID="imgCalendar" runat="server" ImageUrl="~/App_Themes/Sugar2006/images/Calendar_scheduleHS.png" ImageAlign="Middle" />
<asp:CalendarExtender ID="ce" runat="server" TargetControlID ="tbDate" PopupButtonID="imgCalendar" />
<asp:MaskedEditExtender ID="mex" runat="server"
TargetControlID="tbDate"
Mask="99/99/9999"
MaskType="Date"
MessageValidatorTip="true"
OnFocusCssClass="MaskedEditFocus"
OnInvalidCssClass="MaskedEditError" />
<asp:MaskedEditValidator ID="mev" runat="server"
ControlToValidate="tbDate"
ControlExtender="mex"
Display="Dynamic"
InvalidValueMessage="This date is invalid!" Font-Bold="True"
ForeColor="#D50000" />
<asp:RequiredFieldValidator runat="server" ID="DReq"
ControlToValidate="tbDate"
Display="None"
ErrorMessage="A Date is required." />
<asp:ValidatorCalloutExtender runat="Server" ID="DReqE"
TargetControlID="DReq"
HighlightCssClass="validatorCalloutHighlight" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
<br />
<asp:Label ID="lblSave" runat="server" Text="**After Each Test Entry Please Save." ForeColor="#D50000"></asp:Label>
</ContentTemplate>
<Triggers>
<asp:AsyncPostBackTrigger ControlID="ddlResult" EventName="SelectedIndexChanged" />
</Triggers>
</asp:UpdatePanel>
<asp:Content ID="Content1" ContentPlaceHolderID="cntSidebar" runat="server">
<asp:Button ID="btnSave" runat="server" Text="Save" Width="80%"
onclick="btnSave_Click"/> <br />
<asp:Button ID="btnClose" runat="server" Text="Close" Width="80%"
onclick="btnClose_Click" CausesValidation="false"/>
</asp:Content>
Have you tried setting the following properties on the Commit button:
CausesValidation="true" ValidationGroup="vgMyGroup"
Also, try setting the validation controls property: ValidationGroup="vgMyGroup"
Another suggestion could be to do a postback on the Commit button's click event and check for
if(Page.IsValid)...
I would be interested to see if setting the ValidationGroup property persists across the ASP content controls..

Datalist in vb. Trying to get the specific values of a rows or cells in datalist

I have a datalist in vb web form.
How can i get the value in a specific rows and cells of a datalist?
I could do it for detailsview but how to do it for datalist??
Below is my code for detailsview:
Dim selectedCommentAns As String = DetailsView.Rows(0).Cells(1).Text
I tried the same way for datalist but it dont have rows and cells to be selected.
This is the asp markup of my datalist:
<asp:DataList ID="DataListPhotoGallery" runat="server" CellPadding="5"
CellSpacing="12" DataKeyField="PhotographerPhotoId"
DataSourceID="SqlDataSourcePhotoGallery" RepeatColumns="3">
<ItemTemplate>
<asp:Image ID="Image1" runat="server" BorderColor="#C7B273"
BorderStyle="Groove" BorderWidth="12px" Height="200px"
ImageUrl='<%# Eval("PhotographerPhotoImgPath", "images/UserUploadedPhoto/{0}") %>'
Width="220px" />
<br />
Photo No:
<asp:Label ID="PhotographerPhotoIdLabel" runat="server"
Text='<%# Eval("PhotographerPhotoId") %>' />
<br />
Photo Description:
<asp:Label ID="PhotographerPhotoDescLabel" runat="server"
Text='<%# Eval("PhotographerPhotoDesc") %>' />
<br />
Photo Name:
<asp:Label ID="PhotographerPhotoImgNameLabel" runat="server"
Text='<%# Eval("PhotographerPhotoImgName") %>' />
<br />
Photographer Name:
<asp:Label ID="PhotographerIdLabel" runat="server"
Text='<%# Eval("PhotographerName") %>' />
<br />
<asp:Button ID="AddCommentBtn" runat="server"
CommandArgument='<%# Eval("PhotographerPhotoId") %>' Font-Bold="True"
Font-Size="Medium" onclick="AddCommentBtn_Click" Text="Add Comment" />
<asp:Button ID="Button2" runat="server"
CommandArgument='<%# Eval("PhotographerPhotoId") %>' Font-Bold="True"
Font-Size="Medium" onclick="Button2_Click" Text="Order Photo" />
<br />
Instead of Rows and Cells, DataList has a property named Items that lets you access its collection of data-bound items:
Dim itemIndex As Integer = 9
Dim label As Label = DataListPhotoGallery.Items(itemIndex).FindControl("PhotographerPhotoIdLabel")
Dim text As String = label.Text
If you know the row and column indexes but not the item index, then you can calculate the item index like this:
If RepeatDirection is Horizontal: itemIndex = rowIndex * RepeatColumns + columnIndex
If RepeatDirection is Vertical: Post a comment if you need this because it's rather complicated.
You can access items using
DataListPhotoGallery.Items
If you want to access specific item, the you need to find object you are looking for. In this case you want to get a value of PhotographerPhotoIdLabel label.
var PhotographerPhotoIdLabel = DataListPhotoGallery.Items[itemsId].FindControl("PhotographerPhotoIdLabel") as Label;
var yourString = PhotographerPhotoIdLabel.Text;
Hope that helps
You can use the concern datasource to get the value. Please refer the below code to get the required value.
Dim dv As DataView
dv = CType(SqlDataSource1.Select(DataSourceSelectArguments.Empty), DataView)
selectedCommentAns = dv.Table.Rows[0][1]
Hope this will help.

asp.net binding problem

I have in my code behind the following property
public string Firstname {get;set;}
when I want to bind it to some textbox I do the following:
<asp:TextBox runat="server" ID="txtFirstname" Text='<%# Bind("Firstname") %>'/>
then I want value put in this textbox to be set in my Firstname property (because I want to process it e.g. save this value) in my presenter.
Why it doesn't work?
EDIT
Here is the aspx
<formview runat="server" ID="myFormView">
<p>Firstname <asp:TextBox ID="txtFirstName" runat="server" Text='<%# Eval("Firstname") %>' /></p>
<p>Lastname <asp:TextBox ID="txtLastName" runat="server" /></p>
<input type="button" title="send" runat="server" id="btnSend" />
</formview>
It will bind in the page load but you have to tell it what to bind to in mark up or in code. You didn't say where or how you're storing your data and it sounds like you are trying to insert new data so...
Here is a tutorial on the sqldatasource.
SQL Datasource Tutorial
Here is a turorial on the formview:
Formview Tutorial
Here is a simple one I whipped up...(NOTE: I did not test the below code, so if I forgot somehting my apologies, but it should give you a good start).
<asp:SqlDataSource ID="SqlDataSource1"
runat="server"
ConnectionString="Connection string for your database here."
SelectCommand="SELECT FirstName, LastName FROM YourTable"
>
</asp:SqlDataSource>
<asp:FormView ID="frmYourForm" DefaultMode="Insert" runat="server" DataSourceID="SqlDataSource1">
<EditItemTemplate>
<asp:TextBox ID="txtFirstName" runat="server" Text='<%# Bind("FirstName") %>'></asp:TextBox>
<br />
<asp:TextBox ID="txtLastName" runat="server" Text='<%# Bind("LastName") %>'></asp:TextBox>
<asp:LinkButton ID="LinkButton1" CommandName="Update" runat="server">Update</asp:LinkButton>
</EditItemTemplate>
<InsertItemTemplate>
<asp:TextBox ID="txtFirstName" runat="server" Text='<%# Bind("FirstName") %>'></asp:TextBox>
<br />
<asp:TextBox ID="txtLastName" runat="server" Text='<%# Bind("LastName") %>'></asp:TextBox>
<asp:LinkButton ID="LinkButton1" CommandName="Insert" runat="server">Insert</asp:LinkButton>
</InsertItemTemplate>
</asp:FormView>
EDIT: Fixed the links to the tutorials...I didn't realize the orginal link didn't show info on the formview.

Unable to get the Datakey value of a selected row in GridView for use in FormView

I have a gridview like this :
<asp:MultiView ID="MvCustomer" runat="server" ActiveViewIndex="0" >
<%--View 1 to List the customers--%>
<asp:View ID="VwCustomersList" runat="server" >
<asp:GridView ID="GvListCustomer" runat="server" AutoGenerateColumns="False"
HorizontalAlign="Center" DataSourceID="OdsGvCustomers" DataKeyNames="CUSNUM"
EnableModelValidation="True" onrowcommand="GvListCustomer_RowCommand" >
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:Label ID="LblCUSNUM" runat="server" Text='<%#Eval("CUSNUM") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<ItemTemplate>
<asp:Label ID="LblCO_NAM" runat="server" Text='<%#Eval("CO_NAM") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<ItemTemplate>
<asp:Label ID="LblCUSCTY" runat="server" Text='<%#Eval("CUSCTY") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<%--<asp:CommandField ButtonType="Button" SelectText="Edit" ShowSelectButton="true" />--%>
<asp:TemplateField>
<ItemTemplate>
<asp:Button ID="BtnSelect" runat="server" Text="Edit" CommandArgument='<%#Eval("CUSNUM")%>' CommandName="Select" />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<ItemTemplate>
<asp:Button ID="BtnDelete" runat="server" Text="Delete" CommandArgument='<%#Eval("CUSNUM")%>' CommandName="Delete" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
<asp:ObjectDataSource ID="OdsGvCustomers" runat="server"
SelectMethod="GetAllCustomers" TypeName="MultiView_EF.BLL.Customers_BLL">
</asp:ObjectDataSource>
</asp:View>
<%--View 2 to show customer details--%>
<asp:View ID="VwCustomerDetail" runat="server" >
<asp:FormView ID="FvCustomerDetails" runat="server" HorizontalAlign="Center"
DataSourceID="OdsFvCustomerDetails" EnableModelValidation="True" DefaultMode="Edit" >
<EditItemTemplate>
CUSNUM:
<asp:TextBox ID="CUSNUMTextBox" runat="server" Text='<%# Bind("CUSNUM") %>' />
<br />
CO_NAM:
<asp:TextBox ID="CO_NAMTextBox" runat="server" Text='<%# Bind("CO_NAM") %>' />
<br />
CUSCTY:
<asp:TextBox ID="CUSCTYTextBox" runat="server" Text='<%# Bind("CUSCTY") %>' />
<br />
<asp:LinkButton ID="UpdateButton" runat="server" CausesValidation="True"
CommandName="Update" Text="Update" />
<asp:LinkButton ID="UpdateCancelButton" runat="server"
CausesValidation="False" CommandName="Cancel" Text="Cancel" />
</EditItemTemplate>
<InsertItemTemplate>
CUSNUM:
<asp:TextBox ID="CUSNUMTextBox" runat="server" Text='<%# Bind("CUSNUM") %>' />
<br />
CO_NAM:
<asp:TextBox ID="CO_NAMTextBox" runat="server" Text='<%# Bind("CO_NAM") %>' />
<br />
CUSCTY:
<asp:TextBox ID="CUSCTYTextBox" runat="server" Text='<%# Bind("CUSCTY") %>' />
<br />
<asp:LinkButton ID="InsertButton" runat="server" CausesValidation="True"
CommandName="Insert" Text="Insert" />
<asp:LinkButton ID="InsertCancelButton" runat="server"
CausesValidation="False" CommandName="Cancel" Text="Cancel" />
</InsertItemTemplate>
<%--<ItemTemplate>
CUSNUM:
<asp:Label ID="CUSNUMLabel" runat="server" Text='<%# Bind("CUSNUM") %>' />
<br />
CO_NAM:
<asp:Label ID="CO_NAMLabel" runat="server" Text='<%# Bind("CO_NAM") %>' />
<br />
CUSCTY:
<asp:Label ID="CUSCTYLabel" runat="server" Text='<%# Bind("CUSCTY") %>' />
<br />
</ItemTemplate>--%>
</asp:FormView>
<asp:ObjectDataSource ID="OdsFvCustomerDetails" runat="server"
SelectMethod="GetCustomerByCusnum" TypeName="MultiView_EF.BLL.Customers_BLL">
<SelectParameters>
<asp:ControlParameter ControlID="GvListCustomer" Name="cusnum"
PropertyName="SelectedValue" Type="String" />
</SelectParameters>
</asp:ObjectDataSource>
</asp:View>
</asp:MultiView>
My idea is that when the user clicks "BtnSelect" I will change the View to the view containing the FormView which has a select method configured to take the SelectedValue of the GridView as an input parameter - it will show the details of the selected customer.
I have done this before "n" number of times but I am not able to get it working this time. The trouble is that when the call for the Select Method of the formview goes to the relevant function - "GetCustomerByCusnum" I have a null value in its parameter "cusnum".
I know that I can write a selecting event and using CommandArgument, parse the value of the selected row and pass it into the Select method as a value but I dont want that solution. I know it works without the "Selecting" method but I cant recall how.
Please help.
By looking at your code, all seems ok, just a single hint, if you are not setting the active view, do it by SetActiveView method of multiview, please do that in button click.
Another thing you can do is: add OdsFvCustomerDetails_Selecting and OdsFvCustomerDetails_Selected events. in Selecting you can see the params and values passed and in Selected you can see e.Exception if there is any error in the query. so it will give you more idea about what exactly is going wrong.
Additional note
Another thing that should be noted is, multivew control works in a way that it binds all the views regardless of whichever is active so it degrades the performance. You may probably find better idea
Yikes. A relic of a question - IIRC I did away with the MV approach for this as we moved list and details section to different aspx pages and used query string parameters. Never got to fix what must have been, in hindsight, some missing parameter assignment.

Resources