ComfortablyNumb
ComfortablyNumb

Reputation: 1456

Check if at least one checkbox is checked Using C#

I have a web form using custom validators (to set textbox borders to red) and I would like to check that at least one of a group of eight checkboxes have been checked (and possibly set the borders for the checkboxes to red too).

As I have a set of if statements making sure a true or false is returned for each checkbox, I thought I could add a counter and if the counter equals 0 to set Page.IsValid to false. Well that idea didn't work. Doesn't look like you can set Page.IsValid directly.

Then I thought to pop the counter value into a hidden field and validate that, but I can't seem to get the syntax right to use a custom validator on a hidden field.

What is the best solution for this?

Thanks

Upvotes: 0

Views: 3870

Answers (1)

peroija
peroija

Reputation: 1982

what's wrong with you customvalidator? all you need is something like


protected void validateCheckBoxes_ServerValidate(object source, ServerValidateEventArgs args)
{
   if(!CheckBox1.Checked && !CheckBox2.Checked && !CheckBox3.Checked)
      args.IsValid = false;
   else
      args.IsValid = true;
}

the if is saying 'if none of the checkboxes are checked, then we have a problem.'

Upvotes: 3

Related Questions