Looping through controls

liunx

Guest
I am trying to loop through controls on a content page using C# in ASP.Net 2.0. When I use this:

foreach (Control ctl in Page.Controls) {
this.comments.text = this.comments.text + ctl.gettype().tostring();
}

It only returns my asp:MasterPage if i type: If(ctl is textbox) { 'do something' } I get nothing. And when I do Page.Controls.Count it returns 1. Cn any one tell me what might be happening. If I need to I can post my html page but I have many many controls on there. they are all run at server and most of the are ListBoxes.

thanks for any info... JoeyDThe Controls property of a page only contains the Controls that are DIRECT children of the page (not grandchildren, etc.) I haven't actually tried but you should be able to go through all Controls if you do it recursively.I can't seem to figure it out recursivly. Could you please list an example of how I would go about doing that. I tried to google it and either didn't know what I was looking for or was using the wrong key words.

thanks for the help,
Joey D.Alright this is going to be rough. Recursion as well as pointers are the hardest concepts I remeber people having when just learning to program. I was hoping you already knew what it was, a common use is to list directory trees. Anyway without having a debugger or anything handy at the moment I'll attempt to give an example. This may not actually compile but hopefully it will at least give you the idea of what is supposed to happen:

void RecursiveExample(ControlCollection ctlCol) {
foreach (Control ctl in ctlCol) {
comments.Text += ctl.GetType.ToString();
RecursiveExample(ctl.Controls);
}
}

The key here is that the function RecursiveExample actually calls itself. You would pass Page.Controls into this function and it would loop through each control in the page which in your case is just the MasterPage I guess, but then it would call itself again passing MasterPage in and loop through all it's controls which in turn would pass each of it's controls in and loop through all of their controls, etc. until every control on the page had been reached. This is an EXPENSIVE operation performance wise but it is a short amount of code and is complete. Unless year REALLY need every single control on the page I'd suggest you use some other method to do whatever it is you are trying to do. If however you really do need every single control on the page this is the way to do it.

If you decide to go with recursion perhaps you can at least start at a non-root node. In other words if Page is only ever going to contain MasterPage then start at masterpage instead, that will reduce the iterations by one. Even better if all the controls you actually need access to are in a single div or table then start there instead of Page.Thanks this is exactly what I need. So I can create a DIV tag and call something like DisplayControl(DIVID.Controls); ?
 
Back
Top