How to get the SelectedValue of all List controls that are present in a Page

This article describes how to get the selected values of all list controls present in a page using just a single method.

One of the common requirements I see as required by developers is to create a Questionarre which consists of many questions with Radio Button Options as answers.

To loop through all the radiobuttons and get the selected value of them, its tedious if you write code for each and every radiobutton.

The following code accomplishes the task.

private void Button1_Click(object sender, System.EventArgs e)

{



foreach(System.Web.UI.Control ctl in this.Page.Controls)

{

LoopAllControls(ctl);

}

}


public void LoopAllControls(System.Web.UI.Control oControl)

{

foreach(System.Web.UI.Control frmControl in oControl.Controls)

{

if(frmControl.GetType().ToString()=="System.Web.UI.WebControls.RadioButtonList")

{

RadioButtonList rList=new RadioButtonList();

rList=(RadioButtonList)frmControl;

Response.Write(rList.SelectedValue);

}

if(frmControl.HasControls())

{

LoopAllControls(frmControl);

}

}

}


The above code just Response.Writes the selected values of the radio button lists. You can have as many radio button lists as you want in the page. The above code would work for the same.

However, if you want to find some total or store, you can use a variable to get each value.

Hope it helps.

Print | posted on Monday, April 25, 2005 7:37 AM

Comments on this post

# re: How to get the SelectedValue of all List controls that are present in a Page

Requesting Gravatar...
nice post admin.thankss
Left by mario oyunları on Sep 21, 2009 10:39 AM

# re: How to get the SelectedValue of all List controls that are present in a Page

Requesting Gravatar...
hi
great post. thanks.
Left by mario oyunları on Jan 04, 2010 3:08 AM

Your comment:

 (will show your gravatar)