Search code examples
c#asp.netcheckboxlist

How to check if at least one checkbox is checked?


Im trying to bind my data into gridview only when at least one checkbox is checked in each checkboxlist. However it does not seem to work as when I click on submit it with no checkbox checked it still go in the bind statement and did not display the text message in the label.

Where did it gone wrong in my code? please help

if (IsPostBack)
{
   if (CheckBoxList1.SelectedValue != null && CheckBoxList2.SelectedValue != null)
   {
      Bind();
   }
   else if (CheckBoxList1.SelectedValue == String.Empty)
   {
      LABEL1.Text = ("Please select at least one checkbox();
   }
   else if (CheckBoxList2.SelectedValue == String.Empty)
   {
      LABEL2.Text = ("Please select at least one checkbox").ToString();
   }

Solution

  • the If(IsPostback) I think is the culprit. If your page has been refreshed by a button (PostBack) then your checkbox list will Bind(). So everytime you click a button anywhere in the page, your list gets refreshed which makes your selected boxes removed.

    Try to change the If(IsPostBack) into If(!IsPostBack)

    EDIT:

    Oh got it, your .SelectedValue is a string, therefore its never a null.

    Change this

    if(CheckBoxList1.SelectedValue != null && CheckBoxList2.SelectedValue != null)
    

    to this

    if(CheckBoxList1.SelectedValue != String.Empty && CheckBoxList2.SelectedValue != String.Empty)
    

    and revert back the If(!IsPostBack) to If(IsPostBack) as it seems this code event is under a button_click or something, not the thing I assumed as PageLoad.

    please approach for concerns. thanks