How to check that at least one RadioButtonList has an item selected?
I have 20 RadioButtonList
s on a page.
I need to create a validation method to ensure that at least one of these RadioButtonList
s has an item selected.
What kind of validation would I need to use for 开发者_运维知识库this?
EDIT: Updated question based on comments and clarification.
If you are validating against multiple RadioButtonList
s 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.
You could set a default for your RadioButtonList which would mean a user could never not select an option and you would not need all the validation code
<asp:RadioButtonList ID="RadioButtonList1" runat="server">
<asp:ListItem Selected="True">Never</asp:ListItem>
<asp:ListItem>Twice A Week</asp:ListItem>
<asp:ListItem>Every Day Baby!</asp:ListItem>
</asp:RadioButtonList>
EDIT As pointed out in a comment below this would not be sufficient by itself as a means of validation. It is good practice to validate all user input on the server-side also.
I use an extension method that works for ListControls
public static bool IsAnyItemSelected(this ListControl input) { return input.Items.Cast<ListItem>().Aggregate(false, (current, listItem) => current | listItem.Selected); }
精彩评论