我正在使用 C# ASP.net,并且相对较新,需要在下面完成。
在我的 VS2010 Web 应用程序项目中,我有 webform
和一个 Gridview
,它从表中获取数据。
在网格中,我有 Commandfiled
按钮(第 1 列)和带有 Dropdownlist
的项目模板(第 2 列)。
用例是,用户首先从 3 个列表项(H、L 和 M)中选择一个列表项
,然后选择命令按钮。
我无法弄清楚如何从选定的行中提取选定的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 " + ???? ;
}
提前致谢。
最佳答案
GridViewRow
对象提供了方法 FindControl
(与所有容器控件一样)通过其 id 访问行中的控件。例如,如果您的 DropDownList
的 ID 为 MyDropDown
,您可以使用以下命令来访问其选定的值:
GridViewRow row = GridView2.SelectedRow;
DropDownList MyDropDown = row.FindControl("MyDropDown") as DropDownList;
string theValue = MyDropDown.SelectedValue;
// now do something with theValue
这是访问 GridView
中所有控件的推荐方法。您希望尽可能避免执行诸如 row.Cells[#]
之类的操作,因为当您从 GridView 中重新排列或添加/删除列时,它很容易中断。
关于ASP.net Gridview 项模板下拉列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10239316/