How to check that at least one RadioButtonList has an item selected?

Tom picture Tom · Feb 28, 2011 · Viewed 8.8k times · Source

I have 20 RadioButtonLists on a page.

I need to create a validation method to ensure that at least one of these RadioButtonLists has an item selected.

What kind of validation would I need to use for this?

Answer

Kelsey picture Kelsey · Feb 28, 2011

EDIT: Updated question based on comments and clarification.

If you are validating against multiple RadioButtonLists then you need to use a CustomValidator and implement the server side check.

Here is some test markup:

<asp:RadioButtonList ID="rblstTest1" runat="server" ValidationGroup="Test">
    <asp:ListItem Text="Test 1" Value="1" />
    <asp:ListItem Text="Test 2" Value="2" />
    <asp:ListItem Text="Test 3" Value="3" />
</asp:RadioButtonList>
<br /><br />
<asp:RadioButtonList ID="rblstTest2" runat="server" ValidationGroup="Test">
    <asp:ListItem Text="Test 1" Value="1" />
    <asp:ListItem Text="Test 2" Value="2" />
    <asp:ListItem Text="Test 3" Value="3" />
</asp:RadioButtonList><br />
<asp:Button ID="btnTestRb" runat="server" ValidationGroup="Test" Text="Test RBL" 
    OnClick="btnTestRb_Click" />
<asp:CustomValidator runat="server" ValidationGroup="Test" ID="cvTest" 
    ControlToValidate="rblstTest1" OnServerValidate="cvTest_ServerValidate" 
    ValidateEmptyText="true" Enabled="true" display="Dynamic" SetFocusOnError="true"
    ErrorMessage="You must select at least one item." /> 

Use the following extension method to find all the RadioButtonList controls (Source):

static class ControlExtension
{
    public static IEnumerable<Control> GetAllControls(this Control parent)
    {
        foreach (Control control in parent.Controls)
        {
            yield return control;
            foreach (Control descendant in control.GetAllControls())
            {
                yield return descendant;
            }
        }
    }
} 

Then implement the server side CustomValidator check:

protected void cvTest_ServerValidate(object sender, ServerValidateEventArgs e)
{            
    int count = this.GetAllControls().OfType<RadioButtonList>().
        Where(lst => lst.SelectedItem != null).Count();
    e.IsValid = (count > 0);
 }

I have tested the above example and it seems to do exactly what you need. You should be able to switch it to VB pretty easily. Hope this solves your problem.