Reputation: 6132
I have a number of dropdownlists embedded in a gridview. When I submit the page I loop through all the rows of the gridview and use the findcontrol method to get the dropdownlist e.g:
foreach (GridViewRow gvrItem in gvItems.Rows)
{
DropDownList ddlOption = gvrItem.Cells[2].FindControl("ddlOption") as DropDownList;
}
This works nicely, however when I try to get the selected item of the dropdownlist e.g:
ddlOption .SelectedItem.Text
It always returns the first item in the list rather than whats actually selecte din the page. Any ideas what I'm doing wrong?
Upvotes: 0
Views: 2859
Reputation: 6132
It turned out to be a quirk of .Net, if you fill the drop down list with ListItem's it won't carry those items into the ViewState. If you fill the drop down list with strings it will. Very odd I know.
e.g.:
DropDownList ddl = new DropDownList();
ddl.Add(new ListItem("text", "value")); <----Fails :(
ddl.Add("text"); <---- Works :)
Upvotes: 0
Reputation: 26190
You need to do this after the GridView has been databound. Try calling it in the DataBound event:
protected void GridView1_DataBound(object sender, EventArgs e)
{
foreach (GridViewRow gvrItem in gvItems.Rows)
{
DropDownList ddlOption = gvrItem.Cells[2].FindControl("ddlOption") as DropDownList;
}
string selectedItem = ddlOption.SelectedItem.Text;
}
Upvotes: 1