做了一个通过字符串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                         else
20                             break;
21                     }
22                 }
23                 else
24                 {
25                     return null;
26                 }
27             }
28             return con;
29         }

 

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

 

相关文章:

  • 2021-09-25
  • 2022-12-23
  • 2021-07-06
  • 2021-08-13
  • 2022-12-23
  • 2021-06-14
  • 2021-07-24
  • 2022-12-23
猜你喜欢
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-01-31
  • 2022-01-09
  • 2022-12-23
  • 2021-06-20
相关资源
相似解决方案