Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/asp.net/33.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 如何使用扩展方法在gridview中查找控件_C#_Asp.net_Gridview_Extension Methods - Fatal编程技术网

C# 如何使用扩展方法在gridview中查找控件

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;

我试图在pageload上的gridview中找到dropdownlist。我目前正在使用扩展方法。这是我的扩展方法代码

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在哪个列中