How Can I Check The Selected Values Of Multiple Radiobuttonlists?
I have a HTML form that has multiple RadioButtonLists.
Solution 1:
I've done similar things before (namely, manipulating different validator controls). Here's how I'd do it:
var radioButtons = new List<RadioButtonList>()
{
RadioButtonList1,
RadioButtonList2,
RadioButtonList3,
RadioButtonList4,
};
foreach(RadioButtonList rbl in radioButtons)
{
if (rbl.SelectedValue == "1")
{
value1++;
}
else if (rbl.SelectedValue == "2")
{
value2++;
}
}
You can define the list of RadioButtonList
as a private field within your ASP.NET page or user control
Solution 2:
If you put all RadioButtonLists inside a DIV with runat="server" you can easily loop through only RadioButtonLists inside of that DIV. Here is a simple example that is triggered on Button1 click, you can put a debug point at the end of Button1 click event to see the value of value1 and value2.
ASP.NET Code-Behind:
<div id="myradiolist" runat="server">
<asp:RadioButtonList ID="RadioButtonList1" runat="server">
<asp:ListItem Value="1" Text="1"></asp:ListItem>
<asp:ListItem Value="2" Text="2"></asp:ListItem>
</asp:RadioButtonList>
<asp:RadioButtonList ID="RadioButtonList2" runat="server">
<asp:ListItem Value="3" Text="3"></asp:ListItem>
<asp:ListItem Value="4" Text="4"></asp:ListItem>
</asp:RadioButtonList>
<asp:RadioButtonList ID="RadioButtonList3" runat="server">
<asp:ListItem Value="5" Text="5"></asp:ListItem>
<asp:ListItem Value="6" Text="6"></asp:ListItem>
</asp:RadioButtonList>
<asp:RadioButtonList ID="RadioButtonList4" runat="server">
<asp:ListItem Value="7" Text="7"></asp:ListItem>
<asp:ListItem Value="8" Text="8"></asp:ListItem>
</asp:RadioButtonList>
</div>
<asp:Button ID="Button1" runat="server" Text="Button" onclick="Button1_Click" />
C# Code-Behind:
protected void Button1_Click(object sender, EventArgs e)
{
int value1=0, value2=0;
foreach (Control c in myradiolist.Controls)
{
if (c is RadioButtonList)
{
RadioButtonList rbl = (RadioButtonList)c;
if(rbl.SelectedValue.Equals("1"))
value1++;
if (rbl.SelectedValue.Equals("2"))
value2++;
}
}
}
Post a Comment for "How Can I Check The Selected Values Of Multiple Radiobuttonlists?"