开发者

DropDownList Selected Item Incorrect When Using FindControl

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;
}

Thi开发者_如何学Pythons 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?


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;
}


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 :)
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜