Tuesday, March 24, 2009

Traverse / Loop through all form controls in asp.net

This post explains that how to traverse (loop through) all form controls in asp.net page.

foreach (System.Web.UI.Control ctrl in this.form1.Controls)
{
//here your code
}

Further if you want to get the state or data or manipulate the control, use the below code:
Here I am checking that at least one DropDownList item is selected out of all DropDownLists in the current webform.

bool isSelected = false;

foreach (System.Web.UI.Control ctrl in this.form1.Controls)
{

if (ctrl.GetType() == typeof(System.Web.UI.WebControls.DropDownList))
{
DropDownList ddl = (DropDownList)ctrl;

if (ddl.SelectedItem.Text != “”)
{
isSelected = true;
break;
}
}

}

if (isSelected == true)
{
Response.Write(”selected”);
}
else
{
Response.Write(”none selected”);
}

2 comments:

mathieu_cupryk@hotmail.com said...

if (ctrl.GetType() == typeof(System.Web.UI.WebControls.DropDownList))
{
DropDownList ddl = (DropDownList)ctrl;

if (ddl.SelectedItem.Text != "")
{
WebMsgBox.Show(ddl.SelectedValue.ToString());
break;
}
}
tthis does not work,

Ajay Sharma said...

for mathieu_cupryk@hotmail.com

The webmsgbox class does not waits for the user to click on box each time.

The webmsgbox renders the content and it executes on page postback.
It means if your loop executed 3 times then the message box will be shown to you 3 times continuously after the page postback event.

Also use this code inside this code:

foreach (System.Web.UI.Control ctrl in this.form1.Controls)
{
//here your current code
}

Is your controls inside a panel or container??