I have a GridView with a DropDownList.
The DropDownList items need to be set into the code behind.
I checked online code samples and it looks I am supposed to code it this way:
<asp:GridView ID="DG_Table" runat="server" style="z-index: 1;autogeneratecolumns="False"
onrowcommand="DG_Table_RowCommand"
onrowdatabound="onrowdatabound">
<Columns>
<asp:TemplateField HeaderText="Name" >
<ItemTemplate>
<asp:DropDownList ID="Name" runat="server" Text='<%# Bind("Name") %>'></asp:TextBox>
</ItemTemplate>
<asp:TemplateField HeaderText="field1" >
<ItemTemplate>
<asp:TextBox ID="field1" runat="server" Text='<%# Eval("FieldValue") %>'></asp:TextBox>
</ItemTemplate>
</Columns>
</asp:GridView>
Into code behind:
public void onrowdatabound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
//check if is in edit mode
if ((e.Row.RowState & DataControlRowState.Edit) > 0)
{
DropDownList dropdownlist = (DropDownList)e.Row.FindControl("Name");
dropdownlist.DataSource = new List<string>() { "Pete", "Jack", "Steve", "Mike", "Rob", "Jim", "Eric" };
dropdownlist.DataBind();
}
}
}
When debugging, I can see that the debugger enters onrowdatabound.
At this time,
e.Row.RowType == DataControlRowType.Header
This is probably normal at this stage. So the debugger exits the method.
I would expect the debugger to enter onrowdatabound again when attempting to add lines to the DataGrid.
Somehow it does not, so the Datasource is never set and the code later on tries to add a value to the dropdownlist which does not belong to the dropdownlist.Items, causing an execution error:
Additional information: 'Name' has a SelectedValue which is invalid because it does not exist in the list of items.
(which is logical since the dropdownlist.datasource has never been set.
When DG_Table.DataBind() is called, there are 3 rows:
protected void B_Fill_Fennec_Click(object sender, EventArgs e)
{
List<fennec> list_fennec = new List<fennec>() { new fennec("Pete", "dev"), new fennec("Jack", "butcher"), new fennec("Steve", "wood chopper"), };
GridView1.DataSource = list_fennec.Select(x => new { Name = x.Name, FieldValue = x.Occupation });
GridView1.DataBind();
}
Any help appreciated.