C# 如何使用扩展方法在gridview中查找控件
我试图在pageload上的gridview中找到dropdownlist。我目前正在使用扩展方法。这是我的扩展方法代码C# 如何使用扩展方法在gridview中查找控件,c#,asp.net,gridview,extension-methods,C#,Asp.net,Gridview,Extension Methods,我试图在pageload上的gridview中找到dropdownlist。我目前正在使用扩展方法。这是我的扩展方法代码 public static class Extensions { public static Control FindByID(this Control root, string ID) { if (root.ID == ID) { return root;
public static class Extensions
{
public static Control FindByID(this Control root, string ID)
{
if (root.ID == ID)
{
return root;
}
foreach (Control control in root.Controls)
{
Control foundControl = FindByID(control, ID);
if (foundControl != null)
{
return foundControl;
}
}
return null;
}
}
和页面加载
protected void Page_Load(object sender, EventArgs e)
{
Control controlToFind = GridView1.FindByID("DropDownList3");
DropDownList dropDownList3 = controlToFind as DropDownList;
string a = dropDownList3.Text;
}
但是获取空引用异常
请提供帮助并建议其他最佳方法。在
foreach
循环中设置断点,并逐步完成每个迭代。找不到控件,因此需要检查原因。这比询问这里的任何人为什么它可能不起作用要有用得多,因为我们看不到您的控件。即使它起作用,您想在GridView
中找到什么DropDownList
?第一排还是最后一排还是中间的一排?使用右侧的NamingContainer
(GridViewRow
),例如使用GridView1.SelectedRow.FindControl(“DropDownList 3”)
,代替这种容易出错的方法。同时显示asp标记
,以便我们可以查看您是否在模板中使用了正确的赋值DropDownList dropDownList3=row.FindControl(“dropDownList3”)作为DropDownList
注意我的行的位置
您是否考虑过在GridView1\u RowDataBound
事件中查找。。否则,您如何知道在gridview中选择了与下拉列表相关的哪一行。。。??或者查看GridView1\u行更新event。。查找页面加载的事件顺序。。当您认为datagridview在页面加载时可用时。。它实际上是GridView1.SelectedRow.Cells[1].FindControl(“dropdownlist 3”)作为GridView,但您应该知道dropdownlist在哪个列中