I can't find the controls I want when trying to update my gridview. The controls are textboxes and a dropdownlist from an EditItemTemplate. However, if I try to find a label in ItemTemplate it works just fine. The problem seem to be that it "jumps out" of edit mode before I have a chance to get the controls.
Markup for my gridview:
<asp:GridView ID="ProductGridView" runat="server" AllowPaging="True" AllowSorting="True"
AutoGenerateColumns="False" DataKeyNames="Id" OnRowEditing="ProductGridView_RowEditing"
OnRowCancelingEdit="ProductGridView_RowCancelingEdit" OnRowUpdating="ProductGridView_RowUpdating"
OnRowDeleting="ProductGridView_RowDeleting" OnRowDataBound="ProductGridView_RowDataBound">
<Columns>
<asp:CommandField ShowDeleteButton="True" ShowEditButton="True" CausesValidation="false" />
<asp:TemplateField HeaderText="Name" SortExpression="Name">
<EditItemTemplate>
<asp:TextBox ID="txtName" runat="server" Text='<%# Bind("Name") %>'></asp:TextBox>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="lblName" runat="server" Text='<%# Eval("Name") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Quantity" SortExpression="Quantity">
<EditItemTemplate>
<asp:TextBox ID="txtQuantity" runat="server" Text='<%# Bind("Quantity") %>'></asp:TextBox>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="lblQuantity" runat="server" Text='<%# Eval("Quantity") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Family" SortExpression="Family.Name">
<EditItemTemplate>
<asp:DropDownList ID="ddlFamily" runat="server" OnInit="ddlFamily_Init">
</asp:DropDownList>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="lblFamily" runat="server" Text='<%# Eval("Family.Name") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
This is the code-behind from my RowUpdating method. How do I reach the controls from the EditItemTemplate? Am I missing something really simple?
protected void ProductGridView_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
// Get the controls
GridViewRow row = ProductGridView.Rows[e.RowIndex];
Label lblName = (row.FindControl("lblName") as Label); // Returns this label, from the row being edited, just fine
TextBox txtName = (row.FindControl("txtName") as TextBox); // null
TextBox txtQuantity = (row.FindControl("txtQuantity") as TextBox); // null
DropDownList ddlFamily = (row.FindControl("ddlFamily") as DropDownList); // null
// More code to populate product etc.
}
protected void ProductGridView_RowEditing(object sender, GridViewEditEventArgs e)
{
ProductGridView.EditIndex = e.NewEditIndex;
BindGridView(_productRepo.GetAll());
}