Scroll down dropdown on content page - VS2008
I have a MasterPage and Content page
There are several controls on my content page - dropdown, text boxes, radio buttons.
I want to loop through all the controls and if it is one of the controls above, I want to get the selected value, text, etc.
I know I can access the control directly by name, but since this is my asp.net learning experience, I want to be able to walk through the Controls collection
I tried
foreach(Controls ctrl in Master.Controls)
{
}
but I was unable to get to the controls I needed.
Edit :: I guess I drew the gun too quickly as my intellisense kept failing. I solved the problem with this in the code 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 create a recursive subroutine
source to share
The controls are in the geriarchy. The only control on a page is usually a form (but not always). The form contains controls that are displayed in the tag <form>
. If the form has, for example, <p runat="server">
in it, it <p>
will contain all the controls that appear inside it.
For example,
<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 scroll through controls in the direct content of the control.
- EDIT:
Also, to iterate over all the controls you need to either recursively or iteratively loop over the hierarchy
// This is the recursive version
public void LoopControl(Control parent) {
foreach (Control control in parent) {
// do stuff
LoopControl(control);
}
}
// And then
LoopControl(Page);
source to share