由Page.FindControl想到的Page控件树结构

      前两天同事让我帮他解决一个问题,大体就是在页面中通过控件ID找到并修改DataGrid中的一个DropDownList的SelectedValue,他通过Page.FindControl无法找到。记得以前发现过这个问题,以前就是通过在Page控件树中递归查找解决的,今天顺便对asp.net的Page控件树结构研究了一下。
      下面是我递归查找的函数:
 1public object Myfindcontrol(Control parentcontrols,string id)
 2    {
 3        for (int i = 0; i < parentcontrols.Controls.Count; i++)
 4        {
 5            if (parentcontrols.Controls[i].ClientID == id)
 6                return parentcontrols.Controls[i];
 7            else if (parentcontrols.Controls[i].Controls.Count > 0)
 8            {
 9                if(Myfindcontrol(parentcontrols.Controls[i], id)!=null)
10                    return Myfindcontrol(parentcontrols.Controls[i], id);
11            }

12        }

13        return null;
14    }

15
      
<html>
<body>
  
<h1>Welcome to my Homepage!</h1>
  
<form runat="server">
    What is your name?
    
<asp:TextBox runat="server" ID="txtName"></asp:TextBox>
    
<br />What is your gender?
    
<asp:DropDownList runat="server" ID="ddlGender">
      
<asp:ListItem Select="True" Value="M">Male</asp:ListItem>
      
<asp:ListItem Value="F">Female</asp:ListItem>
      
<asp:ListItem Value="U">Undecided</asp:ListItem>
    
</asp:DropDownList>
    
<br />
    
<asp:Button runat="server" Text="Submit!"></asp:Button>
  
</form>
</body>
</html>


参考自创建动态数据输入用户界面 ,本想自己写些东西,突然发现人家讲的已经很好,偷懒一下吧。
原文地址:https://www.cnblogs.com/end/p/666326.html