I looked at the controls in scope while debugging this issue for selecting a drop down item in a DropDownList in an EditItemTemplate. The issue here, the data is not part of the HTML in the initial form and when the OnRowEditing posts back, there is no information about those edit controls.
If you use the F12 developer tools on your browser page before the OnRowEditing you will not see the editing control as ASP did not written them to the HTML with the initial data bind; this keeps the form data as small as possible. After OnRowEditing, the return will show the editing controls as ASP has now written them to the HTML. The solution I went with was:
- Get the 'selection' information from the current GridView which held the initial data bind and store it in a local string.
- Overwrite the GridView with the new 'Editing' data with a new data bind.
- Get the DropDownList control and set it to the local 'selection' string.
protected void gv_RowEditing(object sender, System.Web.UI.WebControls.GridViewEditEventArgs e)
{
try
{
gv.EditIndex = e.NewEditIndex; // row index being edited
string businessSelection = (gv.Rows[e.NewEditIndex].FindControl("lblFieldName") as Label).Text;
gv.DataSource = GetBusinessData(); gv.DataBind();
(gv.Rows[e.NewEditIndex].FindControl("ddlFieldName") as DropDownList).SelectedValue = businessSelection;
}
catch (Exception ex) { ErrorHandleAndLog(ex); }
}
The field markup looks like this (internal naming conventions and data values removed, of course):
<%-- Field Comment --%>
<asp:TemplateField ItemStyle-HorizontalAlign="Center" FooterStyle-HorizontalAlign="Center">
<HeaderTemplate>
<asp:Label runat="server" Text="Field Name" />
</HeaderTemplate>
<ItemTemplate>
<asp:Label runat="server" ID="lblFieldName" Text='<%# Eval("FieldName") %>' />
</ItemTemplate>
<EditItemTemplate>
<asp:DropDownList runat="server" ID="ddlFieldName" >
<asp:ListItem Text="" />
<asp:ListItem Text="Business Option 1" />
<asp:ListItem Text="Business Option 2" />
<asp:ListItem Text="Business Option 3" />
</asp:DropDownList>
</EditItemTemplate>
<FooterTemplate>
<asp:DropDownList runat="server" ID="ddlNewFieldName">
<asp:ListItem Text="" />
<asp:ListItem Text="Business Option 1" />
<asp:ListItem Text="Business Option 2" />
<asp:ListItem Text="Business Option 3" />
</asp:DropDownList>
</FooterTemplate>
</asp:TemplateField>