1

我有如下的aspx页面。我想使用后面的代码在页面中找到控件。

<html xmlns="http://www.w3.org/1999/xhtml">
    <head runat="server">
      <title></title>
    </head>
<body>
    <form id="form1" runat="server">
      <div>
        <asp:Button ID="Button1" runat="server" Text="Button" onclick="Button1_Click" />
      </div>
   </form>
 </body>
</html>

代码背后

protected void Button1_Click(object sender, EventArgs e)
    {
        string name;
        foreach (Control ctrl in Controls)
        {
            if (ctrl.Controls.Count > 0)
            {
                name = ctrl.GetType().Name;
            }
        }
    }

我无法在循环中获得按钮。即使我添加文本框也无法获取。任何人都知道有什么问题吗?请帮忙。

4

3 回答 3

1

Try This.

protected void Button1_Click(object sender, EventArgs e)
{
    string Name = "";
    string Type = "";
    string Id = "";
    foreach (Control ctr in form1.Controls)
    {
        Name = ctr.GetType().Name;
        Type = ctr.GetType().ToString(); ;
        Id = ctr.ID; // If its server control
    }
}
于 2013-08-11T06:45:19.103 回答
1

ASP.Net renders the page Hierarchically. This means that only top level controls are rendered directly. If any of these top level control contains some child controls, these top level control provide their own Controls property.

For example, in your case Form is the top level control that contains child controls such as Button. So on your button click call a method recursively.

protected void Button1_Click(object sender, EventArgs e)
    {
        DisplayControl(Page.Controls);

     }

    private void DisplayControls(ControlCollection controls)
    {

        foreach (Control ctrl in controls)
        {
            Response.Write(ctrl.GetType().ToString() + "  , ID::" +  ctrl.ID + "<br />");

           // check for child OR better to say nested controls
            if (ctrl.Controls != null)
                DisplayControls(ctrl.Controls);
        }

    }
于 2013-08-11T06:54:09.627 回答
1

这是因为您没有获得页面中的所有控件。您必须递归地获得控件。这是一个扩展方法:

public static class ControlExtensions
{
    public static List<Control> GetChildrenRecursive(this Control control)
    {
        var result = new List<Control>();
        foreach (Control childControl in control.Controls)
        {
            result.Add(childControl);
            if (childControl.Controls.Count > 0)
            {
                result.AddRange(GetChildrenRecursive(childControl));
            }
        }

        return result;
    }
}   

现在您可以按如下方式重写您的代码:

foreach (Control ctrl in this.Page.GetChildrenRecursive())
{
    // Your button element is accessible now.
}
于 2013-08-11T06:34:29.400 回答