I´m using a DetailsView but when updating, I cannot get the OldValues because the DetailsViewUpdateEventArgs.OldValues of ItemUpdating event is always empty. The NewValues has the values ok.
Note: I´m not using a datasource component in my application (SqlDataSource, ObjectDataSource, EntityDataSource, etc.). In this case should I do something manually?
Any ideas will be welcome!
Thanks!
Complementing the information:
I´m using ASP.NET 4.0 (WebForms)
A snippet of code that I believe to be relevant below:
<asp:DetailsView ID="customerDetails" runat="server" AutoGenerateRows="False" EmptyDataText="No data..."
meta:resourcekey="customerDetails"
onitemdeleting="customerDetails_ItemDeleting"
oniteminserting="customerDetails_ItemInserting"
onitemupdating="customerDetails_ItemUpdating"
onmodechanging="customerDetails_ModeChanging"
CssClass="customerDetails" DataKeyNames="CustomerID">
<FooterTemplate>
<asp:LinkButton ID="lnkNew" Text="New" ToolTip="New Customer" CommandName="New" meta:resourcekey="lnkNew" runat="server" />
</FooterTemplate>
<EmptyDataTemplate>
<p><asp:Label ID="lblNoDataHasBeenFound" Text="No data has been found." meta:resourcekey="lblNoDataHasBeenFound" runat="server" /></p>
<asp:LinkButton ID="lnkNew" Text="New" ToolTip="New Customer" CommandName="New" meta:resourcekey="lnkNew" runat="server" />
</EmptyDataTemplate>
<Fields>
<%--CustomerID--%>
<asp:TemplateField HeaderStyle-CssClass="detailsHeader" ItemStyle-CssClass="detailsField">
<HeaderTemplate>
<asp:Label ID="ltrCustomerIdLabel" meta:resourcekey="ltrCustomerId" Text="CustomerID:" runat="server" />
</HeaderTemplate>
<ItemTemplate>
<asp:Label ID="lblCustomerId" Text='<%# Eval("CustomerID") %>' runat="server" />
</ItemTemplate>
<EditItemTemplate>
<asp:Label ID="lblCustomerId" Text='<%# Eval("CustomerID") %>' runat="server" />
</EditItemTemplate>
<InsertItemTemplate>
<asp:TextBox ID="txtCustomerId" Text='<%# Bind("CustomerID") %>' MaxLength="5" width="50px" runat="server" />
<cc1:DataAnnotationsValidator ID="CustomerIdValidator" Type="String" runat="server" ControlToValidate="txtCustomerId" PropertyName="CustomerID" Text="*" SourceType="DataLayerPOCO.Customer, DataLayerPOCO" CssError="validationError" Display="None"/>
</InsertItemTemplate>
<HeaderStyle HorizontalAlign="Right" />
<ItemStyle HorizontalAlign="Left" />
</asp:TemplateField>
<%--CompanyName--%>
<asp:TemplateField HeaderStyle-CssClass="detailsHeader" ItemStyle-CssClass="detailsField">
<HeaderTemplate>
<asp:Literal ID="ltrCompanyNameLabel" meta:resourcekey="ltrCompanyName" Text="Company Name:" runat="server" />
</HeaderTemplate>
<ItemTemplate>
<asp:Literal ID="ltrCompanyName" Text='<%# Eval("CompanyName") %>' runat="server"/>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtCompanyName" Text='<%# Bind("CompanyName") %>' MaxLength="40" Width="310px"
runat="server" />
<cc1:DataAnnotationsValidator ID="CompanyNameValidator" Type="String" runat="server" ControlToValidate="txtCompanyName" PropertyName="CompanyName" Text="*" SourceType="DataLayerPOCO.Customer, DataLayerPOCO" CssError="validationError" Display="None"/>
</EditItemTemplate>
<InsertItemTemplate>
<asp:TextBox ID="txtCompanyName" Text='<%# Bind("CompanyName") %>' MaxLength="40" Width="310px"
runat="server" />
<cc1:DataAnnotationsValidator ID="CompanyNameValidator" Type="String" runat="server" ControlToValidate="txtCompanyName" PropertyName="CompanyName" Text="*" SourceType="DataLayerPOCO.Customer, DataLayerPOCO" CssError="validationError" Display="None"/>
</InsertItemTemplate>
<HeaderStyle HorizontalAlign="Right" />
</asp:TemplateField>
...
...
other fields goes here
...
...
<%--Edit/Insert--%>
<asp:TemplateField HeaderStyle-CssClass="detailsHeader" ItemStyle-CssClass="detailsField">
<ItemTemplate>
<asp:ImageButton ID="imgEdit" ImageUrl="~/img/pencil.png" meta:resourcekey="imgEdit" AlternateText="Edit" ToolTip="Edit Customer" CommandName="Edit" runat="server" CausesValidation="false"/>
<asp:ImageButton ID="imgDelete" ImageUrl="~/img/delete.png" meta:resourcekey="imgDelete" AlternateText="Delete" ToolTip="Delete Customer" CommandName="Delete" OnClientClick="return confirmDelete();" runat="server" CausesValidation="false"/>
</ItemTemplate>
<EditItemTemplate>
<asp:ImageButton ID="imgUpdate" ImageUrl="~/img/accept.png" meta:resourcekey="imgUpdate" AlternateText="Update" ToolTip="Update Customer" CommandName="Update" runat="server" />
<asp:ImageButton ID="imgCancel" ImageUrl="~/img/cancel.png" meta:resourcekey="imgCancel" AlternateText="Cancel" ToolTip="Cancel Edit" CommandName="Cancel" runat="server" CausesValidation="false"/>
</EditItemTemplate>
<InsertItemTemplate>
<asp:ImageButton ID="imgSave" ImageUrl="~/img/disk.png" meta:resourcekey="imgSave" AlternateText="Save" ToolTip="Save Customer Data" CommandName="Insert" runat="server" CausesValidation="true"/>
<asp:ImageButton ID="imgCancelInsert" ImageUrl="~/img/cancel.png" meta:resourcekey="imgCancelInsert" AlternateText="Cancel" ToolTip="Cancel Insert" CommandName="Cancel" runat="server" CausesValidation="false"/>
</InsertItemTemplate>
</asp:TemplateField>
<Fields>
</asp:DetailsView>
The event ItemUpdating is like below:
protected void customerDetails_ItemUpdating(object sender, DetailsViewUpdateEventArgs e)
{
repository = repository ?? new NorthwindRepositoryEF();
string id = e.Keys["CustomerID"] as string;
DataLayerPOCO.Customer customer = repository.GetCustomer(id);
string companyName = (string)e.NewValues["CompanyName"];
string contactName = (string)e.NewValues["ContactName"];
string contactTitle = (string)e.NewValues["ContactTitle"];
string address = (string)e.NewValues["Address"];
string city = (string)e.NewValues["City"];
string region = (string)e.NewValues["Region"];
string postalCode = (string)e.NewValues["PostalCode"];
string country = (string)e.NewValues["Country"];
string phone = (string)e.NewValues["Phone"];
string fax = (string)e.NewValues["Fax"];
// Update Customer with the new data
customer.CompanyName = companyName;
customer.ContactName = contactName;
customer.ContactTitle = contactTitle;
customer.Address = address;
customer.City = city;
customer.Region = region;
customer.PostalCode = postalCode;
customer.Country = country;
customer.Phone = phone;
customer.Fax = fax;
repository.UpdateCustomer(customer);
repository.Save();
//---
customerDetails.ChangeMode(DetailsViewMode.ReadOnly);
BindCustomerDetails();
BindCustomersList();
}
The problem is that if I want to handle the old values, I can´t:
this, evaluates to 0:
int oldValuesCount = e.OldValues.Count;
and this, evaluates to null, even if I alter the value to a new one:
string companyNameOld = e.OldValues["CompanyName"] as string;
It seems the old values are only populated when you have a data source bounded declaratively.
You have two workarounds in this case:
Save any old values you may need in ViewState programtically and retrieve it when you want it. This save a trip to the database.
A better option would to use the customer variable that you define in OnItemUpdating as it queries information from the database and contains all the old values.
Hope it helps.
Related
I have grid with text box for filter data on header.I have button outside the grid.I am using this gridview for filtering the grid by some columns. When I click on button I want to get value from text box and dropdownlist on codebehind.cs, below is my webform.aspx code of gridview,
<asp:Button ID="btngetLocationDate" runat="server" Text="Get Filtered Data" OnClick="getTextBoxValue"></asp:Button>
<asp:GridView ID="TrackerGrid" runat="server" BackColor="#CCCCCC" AllowPaging="True" AutoGenerateColumns="false">
<AlternatingRowStyle HorizontalAlign="Center" VerticalAlign="Middle" />
<Columns>
<asp:TemplateField HeaderText="User ID" SortExpression="User ID">
<ItemTemplate>
<asp:Label ID="lbluserid" runat="server" Text='<%# Eval("User ID") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Customer Name">
<HeaderTemplate>
Full Name:
<asp:DropDownList ID="ddlfullName" runat="server" AutoPostBack="true" OnSelectedIndexChanged="onselectDropdown">
<asp:ListItem Text="ALL" Value="ALL" Selected="True"></asp:ListItem>
</asp:DropDownList>
</HeaderTemplate>
<ItemTemplate>
<asp:Label ID="lblname" runat="server" Text='<%# Eval("Full Name") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Mobile Number">
<HeaderTemplate>
Mobile Number:
<asp:TextBox ID="txtMobilenumber" runat="server" AutoPostBack="true"></asp:TextBox>
</HeaderTemplate>
<ItemTemplate>
<asp:Label ID="lblmobile" runat="server" Text='<%# Eval("Mobile Phone") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Email Address">
<HeaderTemplate>
Email Id:
<asp:TextBox ID="txtemail" runat="server" AutoPostBack="true"></asp:TextBox>
</HeaderTemplate>
<ItemTemplate>
<asp:Label ID="lblemail" runat="server" Text='<%# Eval("Email ID") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Longitude">
<HeaderTemplate>
<asp:Label ID="lbllng" runat="server" Text="Longitude"></asp:Label>
</HeaderTemplate>
<ItemTemplate>
<asp:Label ID="lbllongi" runat="server" Text='<%# Eval("Longitude") %>' Width="70"></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Lattitude">
<HeaderTemplate>
<asp:Label ID="lbllat" runat="server" Text="Lattitude"></asp:Label>
</HeaderTemplate>
<ItemTemplate>
<asp:Label ID="lbllatti" runat="server" Text='<%# Eval("Lattitude") %>' Width="70"></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Activated On">
<HeaderTemplate>
<asp:Label ID="lbldevices" runat="server" Text="Activated On"></asp:Label></br>
</HeaderTemplate>
<ItemTemplate>
<asp:Label ID="lbldevice" runat="server" Text='<%# Eval("Activated On") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Location DateTime" SortExpression="Location DateTime">
<HeaderTemplate>
<asp:Label ID="Label1" runat="server" Text="Location DateTime"></asp:Label></br>
<asp:Label ID="lblStartDate" runat="server" AssociatedControlID="txtStartDate" Text="Start Date"></asp:Label>
<asp:TextBox ID="txtStartDate" runat="server"></asp:TextBox>
<cc1:calendarextender id="CalendarStartDate" runat="server" format="dd/MM/yyyy" targetcontrolid="txtStartDate" popupbuttonid="imgPopup1"></cc1:calendarextender>
<asp:ImageButton ID="imgPopup1" runat="server" ImageUrl="https://cdn4.iconfinder.com/data/icons/small-n-flat/24/calendar-alt-512.png" Height="20px" Width="30px" />
</br>
<asp:Label ID="lblEndDate" runat="server" Text="End Date" AssociatedControlID="txtEndDate"></asp:Label>
<asp:TextBox ID="txtEndDate" runat="server"></asp:TextBox>
<cc1:calendarextender id="CalendarEndDate" runat="server" format="dd/MM/yyyy" targetcontrolid="txtEndDate" popupbuttonid="imgPopup2"></cc1:calendarextender>
<asp:ImageButton ID="imgPopup2" runat="server" ImageUrl="https://cdn4.iconfinder.com/data/icons/small-n-flat/24/calendar-alt-512.png" Height="20px" Width="30px" />
</HeaderTemplate>
<ItemTemplate>
<asp:Label ID="lblDatetime" runat="server" Text='<%# Eval("Location DateTime") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
and I am getting texbox value in codebehind code.
protected void getTextBoxValue(object sender, EventArgs e)
{
DropDownList ddlfullname = (TrackerGrid.HeaderRow.FindControl("ddlfullName") as DropDownList);
string selectedValue = ddlfullname.SelectedItem.Text;
TextBox mobilenumber = (TrackerGrid.HeaderRow.FindControl("txtMobilenumber") as TextBox);
string mobile = mobilenumber.Text;
TextBox email = TrackerGrid.HeaderRow.FindControl("txtemail") as TextBox;
string emailid = email.Text;
TextBox staloc = TrackerGrid.HeaderRow.FindControl("txtStartDate") as TextBox;
string startlocatdate = staloc.Text;
TextBox endloc = TrackerGrid.HeaderRow.FindControl("txtEndDate") as TextBox;
string endlocadate = endloc.Text;
}
I am getting empty value when I debugging this code.I think my code is correct but how i am not getting value of textboxes, i don't understand. Please help me for solving my issue.
Thanks in advance.
You probably did not wrap the DataBind() of the Gridview inside an IspostBack check. If you do not then the values will be rested by the DataBind instead of being saved with ViewState.
protected void Page_Load(object sender, EventArgs e)
{
//not here
TrackerGrid.DataSource = source;
TrackerGrid.DataBind();
if (IsPostBack == false)
{
//but inside an ispostback check
TrackerGrid.DataSource = source;
TrackerGrid.DataBind();
}
}
can anyone tell me what i am missing why my row editing event is not firing.
I am trying to give edit facility in same grid as well as Add new data.
I am able to add new data (new row) but unable to edit existing row for update.
my row editing event is not firing.
<asp:GridView ID="grdHierarchy" runat="server" AllowSorting="True" AutoGenerateColumns="False" CssClass="tableGridBorder" GridLines="None" ShowFooter="True" ShowHeaderWhenEmpty="True" Width="100%" OnRowCommand="grdHierarchy_RowCommand" OnRowDataBound="grdHierarchy_RowDataBound"
OnRowEditing="grdHierarchy_RowEditing">
<AlternatingRowStyle CssClass="AlternateRow" />
<Columns>
<asp:TemplateField HeaderText="Sr.#">
<ItemTemplate>
<asp:Label ID="lblSrNo" runat="server" Text="<%# Container.DataItemIndex + 1 %>"></asp:Label>
</ItemTemplate>
<ItemStyle CssClass="textAlignCenter" />
<HeaderStyle CssClass="textAlignCenter" />
</asp:TemplateField>
<asp:TemplateField HeaderText="Name">
<ItemTemplate>
<asp:Label ID="lblName" runat="server" Text='<%# Bind("Name") %>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:RequiredFieldValidator ID="rfvHierarchyName" runat="server" SetFocusOnError="True" ControlToValidate="txtHierarchyName" ErrorMessage="Enter Reference." ValidationGroup="grpHierarchy">
<asp:TextBox ID="txtHierarchyName" CssClass="textBoxSmall" Style="visibility: visible" runat="server" Text='<%# Bind("Name") %>' MaxLength="50"></asp:TextBox>
</asp:RequiredFieldValidator>
<span style="color: Red;">*</span>
<asp:RegularExpressionValidator ID="regexValiator3" runat="server" ControlToValidate="txtAPReference" ErrorMessage='Invalid Reference.' Display="None" ValidationGroup="grpHierarchy" ValidationExpression='([^<>\"\^])*'>
</asp:RegularExpressionValidator>
</EditItemTemplate>
<FooterTemplate>
<asp:RequiredFieldValidator ID="rfvHierarchyName" runat="server" SetFocusOnError="True" ControlToValidate="txtHierarchyName" ErrorMessage="Enter Reference." ValidationGroup="grpfHierarchy">
<asp:TextBox ID="txtHierarchyName" CssClass="textBoxSmall" Style="visibility: visible" runat="server" Text='<%# Bind("Name") %>' MaxLength="50"></asp:TextBox>
</asp:RequiredFieldValidator>
<span style="color: Red;">*</span>
<asp:RegularExpressionValidator ID="regexValiator4" Display="None" runat="server" ControlToValidate="txtHierarchyName" ErrorMessage='Invalid Reference.' ValidationGroup="grpfHierarchy" ValidationExpression='([^<>\"\^])*'>
</asp:RegularExpressionValidator>
</FooterTemplate>
<ItemStyle CssClass="textAlignLeft" />
<HeaderStyle CssClass="textAlignLeft" />
<FooterStyle CssClass="textAlignLeft" />
</asp:TemplateField>
<asp:TemplateField HeaderText="LevelName">
<ItemTemplate>
<asp:Label ID="lblName" runat="server" Text='<%# Bind("Level.Name") %>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:RequiredFieldValidator ID="rfvLevelName" runat="server" SetFocusOnError="True" ControlToValidate="ddlLevelName" ErrorMessage="Select Level Number." Width="100px" CssClass="redborderlarge" ValidationGroup="grpHierarchy" InitialValue="--Select--">
<asp:DropDownList ID="ddlLevelName" Width="200px" Style="visibility: visible" runat="server">
</asp:DropDownList>
</asp:RequiredFieldValidator><span style="color: Red; margin-top: 4px;">*</span>
</EditItemTemplate>
<FooterTemplate>
<asp:RequiredFieldValidator ID="rfvCustomerName" runat="server" SetFocusOnError="True" ControlToValidate="ddlLevelName" ErrorMessage="Select Customer." ValidationGroup="grpfHierarchy" InitialValue="--Select--">
<asp:DropDownList ID="ddlLevelName" Width="200px" Style="visibility: visible" runat="server">
</asp:DropDownList>
</asp:RequiredFieldValidator><span style="color: Red;">*</span>
</FooterTemplate>
<ItemStyle CssClass="textAlignLeft" />
<HeaderStyle CssClass="textAlignLeft" />
</asp:TemplateField>
<asp:TemplateField HeaderText="Action" ShowHeader="False">
<ItemTemplate>
<asp:LinkButton ID="btnHierarchyEdit" runat="server" CausesValidation="false" CommandName="Edit" Text="Edit"></asp:LinkButton>
</ItemTemplate>
<EditItemTemplate>
<asp:LinkButton ID="btnHierarchyUpdate" runat="server" CommandName="Select" Text="Update" CausesValidation="true" ValidationGroup="grpfHierarchy" OnClick="btnHierarchyUpdate_Click" OnClientClick="return ToggleCursor2(1,'grpAP',true);"></asp:LinkButton>
<asp:LinkButton ID="btnHierarchyCancel" runat="server" CausesValidation="false" CommandName="Select" Text="Cancel" OnClick="btnHierarchyCancel_Click"></asp:LinkButton>
</EditItemTemplate>
<FooterTemplate>
<asp:LinkButton ID="btnHierarchyAdd" runat="server" CausesValidation="true" ValidationGroup="grpfHierarchy" CommandName="New" Text="Add" OnClientClick="return true;"></asp:LinkButton>
</FooterTemplate>
<ItemStyle CssClass="textAlignCenter" />
<HeaderStyle CssClass="textAlignCenter" />
<FooterStyle CssClass="textAlignCenter" />
</asp:TemplateField>
</Columns>
<HeaderStyle CssClass="Header" />
<RowStyle CssClass="Row" />
<FooterStyle CssClass="Header borderBttm" />
</asp:GridView>
and my code behind code is this event is not firing.where I am wrong
protected void grdHierarchy_RowEditing(object sender, GridViewEditEventArgs e)
{
grdHierarchy.EditIndex = e.NewEditIndex;
grdHierarchy.ShowFooter = false;
}
protected void grdHierarchy_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName.Equals("New"))
{
Hierarchy Hierarchy = new Hierarchy();
TextBox txtHierarchyName = (TextBox)grdHierarchy.FooterRow.FindControl("txtHierarchyName");
DropDownList ddlLevelName = (DropDownList)grdHierarchy.FooterRow.FindControl("ddlLevelName");
string HierarchyName = txtHierarchyName.Text.Trim();
bool IsNameExist = Hierarchy.IsNameExist(Session, HierarchyName);
if (IsNameExist == false)
{
Hierarchy.Id = 0;
Hierarchy.Name = HierarchyName;
Hierarchy.LevelId = Convert.ToInt64(ddlLevelName.SelectedValue);
Hierarchy.CreatedDtTm = DateTime.Now;
Hierarchy.ModifiedDtTm = DateTime.Now;
Hierarchy.Save(Session);
fillHierarchyGrid();
}
else
{
cGlobalUI.showPopupMsg(Page, "Hierarchy Name is already Exist", cGlobalUI.MessageType.mtInformation);
}
}
}
I have 2 tables that I want to get data from. The first table is the Contractor table which has the contractors personal information and the second table is the Company table which has 2 columns, CompanyName and CompanyID. Both tables have identical column, CompanyID.
The current code I have has a gridview with a "Select" column, SelectedIndexChanged returns the values from the database to fill textboxes.
What I want to do is get the name of the company as opposed to the companyID filled into the textbox (txtCompany), how can I modify my current code below to do so?
ASPX
<asp:TextBox ID="txtFirstName" runat="server"></asp:TextBox>
<asp:TextBox ID="txtLastName" runat="server"></asp:TextBox>
<asp:TextBox ID="txtPID" runat="server"></asp:TextBox>
<asp:TextBox ID="txtCompany" runat="server"></asp:TextBox>
<asp:GridView ID="TDetails" DataSourceID="SqlDataSource1" DataKeyNames="PersonID" AutoGenerateColumns="false" runat="server" OnSelectedIndexChanged="TDetails_SelectedIndexChanged" >
<HeaderStyle BackColor="gray" ForeColor="White" />
<Columns
<asp:TemplateField>
<ItemTemplate>
<asp:LinkButton ID="lbtnSelect" runat="server" CommandName="Select" Text="Select" />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Last Name">
<ItemTemplate>
<asp:Label ID="lblLastName" runat="server" Text='<%#Eval("LastName") %>' />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="First Name">
<ItemTemplate>
<asp:Label ID="lblFirstName" runat="server" Text='<%#Eval("FirstName") %>' />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Company" Visible="false">
<ItemTemplate>
<asp:Label ID="lblCompany" runat="server" Text='<%#Eval("CompanyID") %>' />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="PersonID" Visible="false">
<ItemTemplate>
<asp:Label ID="lblPID" runat="server" Text='<%#Eval("PersonID") %>' />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
.CS
protected void TDetails_SelectedIndexChanged(object sender, EventArgs e)
{
txtPID.Text = TDetails.DataKeys[TwicDetails.SelectedRow.RowIndex].Value.ToString();
txtLastName.Text = (TDetails.SelectedRow.FindControl("lblLastName") as Label).Text;
txtFirstName.Text = (TDetails.SelectedRow.FindControl("lblFirstName") as Label).Text;
txtCompany.Text = (TDetails.SelectedRow.FindControl("lblCompany") as Label).Text;
}
You can modify your SQL query to fetch the CompanyName as well like how you are fetching the CompanyId and bind it to gridview and set the visibility to false, finally you can set the value of textbox like how you are doing for other controls:-
SQL Query:-
SELECT CompanyId, CompanyName, ....
FROM tblCompany..
Aspx:-
<asp:TemplateField HeaderText="Company" Visible="false">
<ItemTemplate>
<asp:Label ID="lblCompanyName" runat="server" Text='<%#Eval("CompanyName") %>' />
</ItemTemplate>
</asp:TemplateField>
I have a function I've written that you pass in the gridview row, as well as what control type you're attempting to locate. It finds the control as intended, however, it finds it in the incorrect cell.
protected int GetCell(GridViewRow row, string strSection)
{
int intVal = 0;
for (int i = 0; i < row.Cells.Count; i++)
{
intVal = i;
if (strSection == "QueryRate")
{
DropDownList cmbQueryType = row.Cells[i].FindControl("cmbQueryType") as DropDownList;
if (cmbQueryType != null)
{
break;
}
}
else if (strSection == "Name")
{
TextBox txtName = row.Cells[i].FindControl("txtName") as TextBox;
if (txtName != null)
{
break;
}
}
}
return intVal;
}
From my understanding, and directly from the Microsoft page: Searches the current naming container for a server control with the specified id parameter.
So my question is, why is this seemingly finding the control is the wrong column? I can't hard code specific columns, because the columns that show vary based on the the datasource.
Per request, the gridview:
<TDWeb:PageGridView SkinID="pagegrid" EmptyDataText="No unmatched parameters." ID="gvUnmatched" runat="server" AllowSorting="True"
OnSorting="gvUnmatched_Sorting" AutoGenerateColumns="False" OnRowDataBound="gvUnmatched_RowDatabound" OnDataBound="gvUnmatched_DataBound"
OnPreRender="gvUnmatched_PreRender" OnPageIndexChanging="OnFilterUnmatched" DataKeyNames="InternalName"
ShowFooter="true" OnPageSizeChanged="gvUnmatched_PageSizeChanged">
<Columns>
<asp:TemplateField runat="server" ItemStyle-CssClass="c" FooterStyle-CssClass="c">
<HeaderTemplate>
<asp:Label runat="server" Text="Add" />
<asp:CheckBox runat="server" ID="ckbAddAll" />
</HeaderTemplate>
<ItemTemplate>
<asp:CheckBox runat="server" ID="ckbAdd" EnableViewState="true" />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField runat="server" ItemStyle-CssClass="c">
<HeaderTemplate>
<asp:Label runat="server" Text="Ignore" />
<asp:CheckBox runat="server" ID="ckbIgnoreAll" />
</HeaderTemplate>
<ItemTemplate>
<asp:CheckBox runat="server" ID="ckbIgnore" />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField runat="server" HeaderText="Name" SortExpression="Name" ItemStyle-CssClass="l">
<HeaderTemplate>
<asp:LinkButton runat="server" Text="Name" CommandName="Sort" CommandArgument="Name" />
<td:HelperBox ID="HelperBox5" runat="server" ToolTipText="Set the Name for this parameter. This value must be unique to the CAN Bus or ECU and is the value used throughout the DAP system to reference this parameter." />
</HeaderTemplate>
<ItemTemplate>
<asp:TextBox runat="server" ID="txtName" Width="250" MaxLength="256" style="background-color:inherit" Text='<%# Bind("Name") %>' />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField runat="server" ItemStyle-CssClass="l" SortExpression="Description">
<HeaderTemplate>
<asp:LinkButton runat="server" Text="Description" CommandName="Sort" CommandArgument="Description" />
<td:HelperBox ID="HelperBox4" runat="server" ToolTipText="Set the Description for this parameter. This value is for informational purposes only. Not required." />
</HeaderTemplate>
<ItemTemplate>
<asp:TextBox runat="server" ID="txtDescription" Width="175" MaxLength="500"
TextMode="multiline" style="background-color:inherit" Text='<%# Bind("Description") %>' />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField runat="server" HeaderText="Length (bits)" SortExpression="LengthBits" ItemStyle-CssClass="r">
<ItemTemplate>
<asp:Label runat="server" ID="txtSizeBits" Text='<%# (int)Eval("LengthBits") + (int)Eval("LengthBytes") * 8 %>' style="background-color:inherit" />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField runat="server" AccessibleHeaderText="SourceAddress" HeaderText="SA" SortExpression="Sources" ItemStyle-CssClass="r">
<ItemTemplate>
<asp:Label runat="server" ID="txtSources" Text='<%# Eval("SourceString") %>' />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField runat="server" AccessibleHeaderText="ID" HeaderText="ID/Address" SortExpression="IDorAddress" ItemStyle-CssClass="r">
<ItemTemplate>
<asp:Label runat="server" ID="txtIDorAddress" Text='<%# Eval("IDorAddress") %>' />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField runat="server" HeaderText="Data Type" SortExpression="Datatype" ItemStyle-CssClass="l">
<ItemTemplate>
<asp:Label runat="server" ID="txtDatatype" Text='<%# Bind("Datatype") %>' />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField runat="server" AccessibleHeaderText="QueryRate" ItemStyle-CssClass="r" SortExpression="QueryRate" HeaderText="Query Rate">
<HeaderTemplate>
<asp:Label runat="server" Text="Rate" />
<td:HelperBox ID="HelperBox9" runat="server" ToolTipText="Set the Query Type and Rate for this parameter (if applicable). If set, this value overrides the default Query set below." />
</HeaderTemplate>
<ItemTemplate>
<asp:Label runat="server" ID="lblCANRate" Text='<%# Eval("QueryRateString", "{0} s") %>' Visible='<%# m_SelectedFile.ImportType == App_Code.DAPConfig.ParameterFileImport.EImportType.CANDBC || (m_SelectedFile.ImportType == App_Code.DAPConfig.ParameterFileImport.EImportType.J1939DBC && ((int)Eval("QueryRate")) > 0) %>' />
<asp:DropDownList runat="server" ID="cmbQueryType" style="background-color:inherit" Visible='<%# m_SelectedFile.ImportType != App_Code.DAPConfig.ParameterFileImport.EImportType.CANDBC && (m_SelectedFile.ImportType != App_Code.DAPConfig.ParameterFileImport.EImportType.J1939DBC || (int)Eval("QueryRate") <= 0) %>' />
<asp:Panel runat="server" id="pnlRate" style="display:none" ><asp:TextBox runat="server" ID="txtRate" Width="50" MaxLength="6" style="background-color:inherit" />s</asp:Panel>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField runat="server" HeaderText="Category" ItemStyle-CssClass="l">
<HeaderTemplate>
<asp:Label runat="server" Text="Category" />
<td:HelperBox ID="HelperBox10" runat="server" ToolTipText="Set the Category with which to group this parameter, or create a new category." />
</HeaderTemplate>
<ItemTemplate>
<asp:DropDownList runat="server" ID="cmbCategory" style="background-color:inherit" >
<asp:ListItem Value="_New_" Text="Add New..." />
</asp:DropDownList>
<br />
<asp:TextBox Width="100" MaxLength="50" runat="server" ID="txtCategory" style="display:none;background-color:inherit" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</TDWeb:PageGridView>
ok - turns out that calling row.cells(0).FindControl("") is the equivalent of calling row.FindControl("") because FindControl() operates within the current NamingContainer. And all the cells in a given row have the same NamingContainer, specifically {System.Web.UI.WebControls.GridViewRow}
If all you need is to determine the column index of a given control try this (pardon the VB):
Public Function getCellIndexByName(ByVal row As GridViewRow, ByVal ColumnName As String) As Integer
For ci As Integer = 0 To row.Cells.Count - 1
If CType(row.Cells(ci), DataControlFieldCell).ContainingField.ToString() = ColumnName Then
Return ci
End If
Next
Return -1
End Function
If you know the ID of the control that you are trying to find, you don't need to specify the cell. You can find it by looking in the whole row.
DropDownList cmbQueryType = row.FindControl("cmbQueryType") as DropDownList
This way you avoid the problem of incorrect cell index.
I have label within a DetailsView.
I need to change Text property of this Label inside the DetailsView after event ItemInserted has been trigged.
Script does not throws any error, but the Label does not change its text property.
Any ideas what I am doing wrong?
Thanks for your time!
Markup:
<asp:DetailsView ID="uxInsertAuthorInput" runat="server" AutoGenerateRows="False"
DataKeyNames="AuthorId" DataSourceID="EntityDataSourceCreateAuthor" DefaultMode="Insert"
OnItemInserting="uxInsertAuthor_ItemInserting" OnItemInserted="uxInsertAuthorInput_ItemInserted">
<Fields>
<asp:TemplateField HeaderText="First Name" SortExpression="FirstName">
<ItemTemplate>
<asp:Label ID="uxFirstNameDisplayer" runat="server" Text='<%# Bind("FirstName") %>' />
</ItemTemplate>
<InsertItemTemplate>
<asp:TextBox ID="uxFirstNameInput" runat="server" Text='<%# Bind("FirstName") %>' />
<asp:RequiredFieldValidator ID="uxRequiredFieldValidatorFirstName" runat="server"
ControlToValidate="uxFirstNameInput" ErrorMessage="First Name Field is required">*</asp:RequiredFieldValidator>
</InsertItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Last Name" SortExpression="LastName">
<ItemTemplate>
<asp:Label ID="uxLastNameDisplayer" runat="server" Text='<%# Bind("LastName") %>' />
</ItemTemplate>
<InsertItemTemplate>
<asp:TextBox ID="uxLastNameInput" runat="server" Text='<%# Bind("LastName") %>' />
<asp:RequiredFieldValidator ID="uxRequiredFieldValidatorLastName" runat="server"
ControlToValidate="uxLastNameInput" ErrorMessage="Last Name Field is required">*</asp:RequiredFieldValidator>
</InsertItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="UserId" SortExpression="UserId">
<InsertItemTemplate>
<asp:DropDownList ID="uxUserListSelector" runat="server" />
<asp:Label ID="uxAllert" runat="server" Text="Label" />
</InsertItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Profile" SortExpression="ContentAuthor">
<ItemTemplate>
<asp:Label ID="uxContentAuthorDisplayer" runat="server" Text='<%# Bind("ContentAuthor") %>' />
</ItemTemplate>
<InsertItemTemplate>
<asp:TextBox ID="uxContentAuthorInput" runat="server" Text='<%# Bind("ContentAuthor") %>' />
</InsertItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="NoteInternal" SortExpression="NoteInternal">
<ItemTemplate>
<asp:Label ID="uxNoteInternalDisplayer" runat="server" Text='<%# Bind("NoteInternal") %>' />
</ItemTemplate>
<InsertItemTemplate>
<asp:TextBox ID="uxNoteInternalInput" runat="server" Text='<%# Bind("NoteInternal") %>' />
</InsertItemTemplate>
</asp:TemplateField>
<asp:CommandField ShowInsertButton="True" />
</Fields>
</asp:DetailsView>
Code-behind:
protected void uxInsertAuthorInput_ItemInserted(object sender, DetailsViewInsertedEventArgs e)
{
String FirstName = e.Values["FirstName"].ToString();
String LastName = e.Values["LastName"].ToString();
uxMessageDisplayer.Text = string.Format("Author: {0} {1} has been added.", FirstName, LastName);
// problem is here:
Label myAllert = (Label)uxInsertAuthorInput.FindControl("uxAllert");
myAllert.Text = "TEST";
}
you need to use ItemUpdated event of detailsview rather than ItemInserted event
ItemUpdated: Occurs when an Update button within a DetailsView control is clicked, but after the update operation. from here
I am sure this will resolve issue 100%