2012-04-20 125 views
3

我正在使用C#ASP.net,并且对它有新意,并且需要在下面完成。ASP.net Gridview Itemtemplate下拉列表

在我的VS2010 Web应用程序项目中,我有webformGridview,它从表中提取数据。

在网格中,我有Commandfiled Button(column1)和Item template with Dropdownlist(column2)。

用例是,用户首先从3个列表项(H,L和M)中选择一个listitem,然后选择命令按钮。

我不能够提前从选定的行弄清楚如何提取选择listitem

protected void GridView2_SelectedIndexChanged(object sender, EventArgs e) 
{ 

    GridViewRow row = GridView2.SelectedRow; 
    Label4.Text = "You selected " + row.Cells[4].Text + "."; 
    Label5.Text = "You selected this list item from dropdownlist " + ???? ; 
} 

感谢。

回答

2

GridViewRow对象提供方法FindControl(与所有容器控件一样)通过其id访问行中的控件。例如,如果你的DropDownListMyDropDown一个id,你可以使用下面的方法访问它的设定值:

GridViewRow row = GridView2.SelectedRow; 
DropDownList MyDropDown = row.FindControl("MyDropDown") as DropDownList; 
string theValue = MyDropDown.SelectedValue; 
// now do something with theValue 

这是访问您的GridView所有控件的推荐方法。您希望避免像row.Cells[#]这样的事情尽可能避免,因为当您重新安排或添加/删除GridView中的列时,它很容易中断。

+0

谢谢您的解决方案,并提示避免细胞指数 – user219628 2012-04-20 02:24:45