user2015043
user2015043

Reputation: 11

C# - find page control in the page

I has aspx page as below. I want to find the control in the page using code behind.

<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>

Code Behind

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

I can't get the button in the loop. Even i add textbox it also can't get. Any one has idea what wrong? Please help.

Upvotes: 1

Views: 2559

Answers (3)

Kamyar
Kamyar

Reputation: 18797

This is because you're not getting all the controls in your page. You'd have to get controls recursively. Here's an extension method:

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;
    }
}   

Now you can rewrite your code as follows:

foreach (Control ctrl in this.Page.GetChildrenRecursive())
{
    // Your button element is accessible now.
}

Upvotes: 1

R.C
R.C

Reputation: 10565

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);
        }

    }

Upvotes: 1

Raghubar
Raghubar

Reputation: 2788

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
    }
}

Upvotes: 1

Related Questions