Monday, November 28, 2011

Iterating all controls on an ASP.Net form

While trying to debug an asp.net viewstate error, I needed to iterate all of the controls on an ASP.Net page and display their name, level in the tree structure and order. I wrote the following recursive function to do so:


private void DebugWriteAllControls(Control startControl, int depth)
{
System.Diagnostics.Debug.WriteLine("Depth: " + String.Format("{0:D3}", depth) + " Cntrl: " + startControl.ID);
if (startControl.Controls != null)
{
int ControlCount = startControl.Controls.Count;
for (int x = 0; x < ControlCount; x++)
{
DebugWriteAllControls(startControl.Controls[x], depth + 1);
}
}
}


The function can be called from any control and will iterate through all child controls while outputing their information to the output window in Visual Studio.