Active Server Pages Programming (ASP)/checboxlist validation
Expert: Srini Nagarajan - 8/14/2007
QuestionHey,
I hav an application which uses a checkboxlist with 6 checkboxes. I would like to make sure at least one of the checkboxes is checked. I have tried many versions of validation but cannot get this to work. Can you shed any light on what to do?
Cheers
Paul
AnswerHi,
You can use Custom validation to check CheckboxList
Here is the sample code.
private void User_Choice(object sender, ServerValidateEventArgs e)
{
int counter = 0;
for(int i=0;i<chkboxPeeps.Items.Count;i++)
{
if(chkboxPeeps.Items[i].Selected)
{
counter++;
}
e.IsValid = (counter == 0) ? false : true;
}
}
public void ValidateForm(object sender, EventArgs e)
{
if(Page.IsValid)
{
//success
}
else
{
failed validation msg
}
}
<asp:CheckBoxList id="chkboxPeeps" runat="server"/>
<asp:CustomValidator id="customvalidation" runat="server" display="dynamic" text="You need to select at least one of the choices to be valid" OnServerValidate="User_Choice"/>
<asp:Button id="btnSubmit" Text="Check" OnClick="ValidateForm" runat="server"/>
Hope this helps!!
-Srini