·您现在的位置: 云翼网络 >> 文章中心 >> 网站建设 >> 网站建设开发 >> ASP.NET网站开发 >> 使用FindControl(id)查找控件 返回值都是Null的问题

使用FindControl(id)查找控件 返回值都是Null的问题

作者:佚名      ASP.NET网站开发编辑:admin      更新时间:2022-07-23

使用FindControl("id")查找控件 返回值都是Null的问题

做了一个通过字符串ID查找页面控件并且给页面控件赋值的功能,过程中遇到了this.FindControl("id")返回值都是Null的问题,记录一下解决办法。

问题的原因是我所要查找的ID控件的父控件不是this所造成的。

所以我写了一个递归方法获取控件:

 1 /// <summary> 2 /// 获取页面中某个控件 3 /// </summary> 4 /// <param name="control">父控件容器</param> 5 /// <param name="id">控件ID</param> 6 /// <returns></returns> 7 public Control GetControl(Control control, string id) 8         { 9             Control con = control.FindControl(id);10             if (con == null)11             {12                 if (control.HasControls())13                 {14                     foreach (Control c in control.Controls)15                     {16                         con = GetControl(c, id);17                         if (con == null)18                             continue;19                         else20                             break;21                     }22                 }23                 else24                 {25                     return null;26                 }27             }28             return con;29         }

使用方法 :TextBox txt = GetControl(this, “textBox1”) as TextBox; //在当前页面中查找ID为“textBox1” 的TextBox控件。