tags:

views:

698

answers:

2

I have a MasterPage and a Content Page

My Content Page has a number of controls, - dropdownlist, text boxes, radio buttons.

I want to loop through all the control and if its one of the controls above then i want to obtain the selectedvalue, text etc

I know I can access the control directly by name, but as this is my learning experience on asp.net, I want to be able to go through the Controls collection

I tried

foreach(Controls ctrl in Master.Controls)
{
}

but I wasnt able to get to the controls I needed.

Edit:: I guess i drew the gun a bit too quick as my intellisense kept failing on me. I solved my issue with this in code behind on my content page

protected void btnSearch_Click(object sender, EventArgs e)
        {
            foreach (Control ctrl in Master.Controls)
            {
                if (ctrl is HtmlForm)
                {
                    foreach(Control formControl in ctrl.Controls)
                    {
                        if (formControl is ContentPlaceHolder)
                        {
                            foreach (Control placeHolderControl in formControl.Controls)
                            {
                                if (placeHolderControl is DropDownList)
                                {
                                    string test = "AA";
                                }
                            }
                        }
                    }

                }

            }
        }

Now to build a recursive routine

A: 

If you are trying to access the content page controls from the master page, you need to access the controls through the appropriate ContentPlaceHolder (on the master page). something like this:

foreach (Control c in ContentPlaceHolder1.Controls)
{
    Response.Write(c.ID );
}
AlexCuse
+1  A: 

The Controls are in a heirarchy. The only control in the page is usually a Form (but not always). The form contains controls that appear in the <form> tag. If the form has for example a <p runat="server"> in it, the <p> will contains all controls that appear inside it.

For instance,

<form runat="server">
  <p runat="server">
    <asp:Label runat="server" />
    <asp:TextBox runat="server" />
  </p>
  <p runat="server">
    <asp:Button runat="server" />
  </p>
</form>

will result in the following structure:

form
 - p
   - label
   - textbox
 - p
   - button

Thus, you must loop through the controls in the directly containing control.

-- EDIT:

Also, to loop through all controls you would need to either recursively or iteratively loop into the heirarchy

// This is the recursive version
public void LoopControl(Control parent) {
    foreach (Control control in parent) {
        // do stuff
        LoopControl(control);
    }
}

// And then
LoopControl(Page);
configurator