Ragnar
Ragnar

Reputation: 212

Check if all radio buttons are selected in C#

I have around 75 radio buttons (before you ask why you need that many radio buttons, lets just say I need them), I have grouped them by 5 in different groups. So, my question is, is there a way I can validate them if in each group at least one radio button is selected before I submit something. SO I have 15 groups like this.

<h4 style="">1 Question? </h4>

<asp:RadioButton ID="RadioButton1"  runat="server" Text="Strongly Disagree" GroupName="Gr1" />
<asp:RadioButton ID="RadioButton2"  runat="server" Text="Disagree" GroupName="Gr1" />
<asp:RadioButton ID="RadioButton3"  runat="server" Text="Uncertain" GroupName="Gr1" />
<asp:RadioButton ID="RadioButton4"  runat="server" Text="Agree" GroupName="Gr1" />
<asp:RadioButton ID="RadioButton5"  runat="server" Text="Strongly Agree" GroupName="Gr1" />

In code behind, on button click I will have something like this. It means I want first to check if user has selected at least one radio buttons from each group before I submit something with SQL Command. Every CMD has different query

if (RadioButton1.Checked)
{
    SqlCommand cmd = new SqlCommand("My query here", con);
    cmd.ExecuteNonQuery();
}

if (RadioButton2.Checked)
{
    SqlCommand cmd = new SqlCommand("My query here", con);
    cmd.ExecuteNonQuery();
}

Upvotes: 0

Views: 1995

Answers (1)

yv989c
yv989c

Reputation: 1543

The following method will give you back the RadioButton controls that are immediate children of a parent Control:

private IEnumerable<RadioButton> GetRadioButtons(Control container, string groupName)
{
    return container.Controls
        .OfType<RadioButton>()
        .Where(i => i.GroupName == groupName);
}

For instance, if the radio buttons with the group name "Gr1" are immediate children of your form, you can get them like this:

var radioButtons = GetRadioButtons(Form, "Gr1");

Checking if any of them are checked could be done like this:

var radioButtonCheckedInGr1 = GetRadioButtons(Form, "Gr1").Any(i => i.Checked);

Hope this helps.

Upvotes: 3

Related Questions