How to add All selection checkbox in ASP.Net CheckBoxList control

Download Sample Project (151.36 kb)

In this post I will discuss how to use ASP.Net CheckBoxList control with an option to include All checkbox which can be used to enable and disable rest of the list depending on the selection. There are two approaches you can take to implement All check box item in the list.

  • AutoPostBack: You can enable AutoPostBack to get server side event when a checkbox is selected and then you can update Selected attribute of each item in CheckBoxList to indicate enable or disabled state depending if All checkbox was disabled or enabled.
  • Client Side onclick: With this approach you can handle click event for each checkbox on client side and then enable or disable list of checkboxes depending on if All checkbox is selected or not.

First approach of AutoPostBack seems easy to implement but will not give a very pleasant expereince to the user. Imagine your self as a user and you have to deal with refresh of the pages everytime you checked or unchecked a check box in the list. And if this list is long and you have to do lot of selections then it will be very frustrating experience for the user. Therefore I would prefer to handle the click event of check boxes in the list and then update state of list of checkboxes on client side itself.

Adding All CheckBox

To add a checkbox that allows All selection, you will either have to add an entry in your dataset to represent that checkbox or you will need to manually add each entry in the checkbox list and the first entry you will add is for All. I prefer to manually add the entries because for handling the client side event, you would need to add some clientside handlers on each checkbox. Following code snippet from the sample project shows how I populated the checkbox list.

void BindOptionsList()
{
   OrderOptionsCheckList.Items.Clear();
   // First add "All" selection item.
   var liAll = new ListItem() 
     { Value = "-1", Text = "All", Selected = _allSelected };
   liAll.Attributes.Add("onclick", 
          string.Format("orderOptionSelected(this,'{0}',{1},{2});", 
            OrderOptionsCheckList.ID, -1, _orderOptions.Count));
   OrderOptionsCheckList.Items.Add(liAll);
   foreach (var option in _orderOptions)
   {
     var li = new ListItem() { Value = option.Id.ToString(), Text = option.Name };
     li.Attributes.Add("onclick", 
       string.Format("orderOptionSelected(this,'{0}',{1},{2});", 
         OrderOptionsCheckList.ID, option.Id, _orderOptions.Count));
     if (_selectedOptions != null && _selectedOptions.Count != 0)
     {
        li.Selected = _allSelected || ItemSelected(option.Id);
     }
     OrderOptionsCheckList.Items.Add(li);
   }
}

As you can see from the code above, I have added onclick event handler for each check box in the list. I have passed the ID checkboxlist control along with number of items in the list so that client side javascript has all the information it needs to manipulate the checkbox list when user clicks in it. As you can see I have used a value of -1 for All checkbox to distinguish it from rest of the list. You can pick any value that will not be a normal value for your actual dataset representing the checkbox items.

Handling Click On Client Side

Following javascript code snippet from sample project shows how I handled click event on each check box.

function orderOptionSelected(elem, listId, value, count) {
  if (value != -1) {
     return;
  }
  for (var i = 0; i < count; i++) {
     var checkBoxId = listId + '_' + (i + 1).toString();
     var checkBox = document.getElementById(checkBoxId);
     if (null == checkBox) continue;
     if (elem.checked) {
       checkBox.checked = true;
       checkBox.disabled = true;
     }
     else {
      checkBox.disabled = false;
     }
  }
}

function processAllCheckBoxSelection() {
  if (allOptionsSelected) {
    for (var i = 0; i < optionsCount; i++) {
      var checkBoxId = optionsListId + '_' + (i + 1).toString();
      var checkBox = document.getElementById(checkBoxId);
      if (null == checkBox) { continue; }
      checkBox.disabled = true;
    }
  }
}

if (window.addEventListener) {
  window.addEventListener('load', processAllCheckBoxSelection, false);
}
else if (window.attachEvent) {
 window.attachEvent('onload', processAllCheckBoxSelection);
}

As you can see when user clicks on All checkbox, javscript enables or disabled all the other checkboxes in the list depending on state of All checkbox. If All is selected then all other checkbox items are put in selected state and disabled.

Handling Selected All CheckBox Selection On Server Side

It may look pretty straight forward that when page posts back you can iterate over all the check boxes in the list and find out what checkbox items are selected and which ones are not. This works as expected when All checkbox is not in SELECTED state. But when you have All selected and rest of the checkbox items are in selected but disabled state, ASP.Net framework treats all disabled checkbox items as not selected and only item that is in selected mode is All. So you have to deal with this behavior accordingly. Following code snippet shows how I implemented post back event for checkboxlist.

void GetSelectedOptions()
{
  if (!IsPostBack)
  {
   return;
  }

  _selectedOptions = new List<int>();
  foreach (ListItem li in OrderOptionsCheckList.Items)
  {
    if (li.Selected)
    {
       _selectedOptions.Add(Convert.ToInt32(li.Value));
    }
  }

  _allSelected = (_selectedOptions.Count != 0 
    && _selectedOptions[0] == -1);
  // If "All" selection is checked then add all items to list.
  if (_selectedOptions.Count == 1 &&
       _selectedOptions[0] == -1)
  {
     _allSelected = true;
     foreach (var option in _orderOptions)
     {
        _selectedOptions.Add(option.Id);
     }
  }

  Session["SelectedOptions"] = _selectedOptions;
}
ASP.Net CheckBoxList
CheckBoxList All Selected

You can see from the code above that when All checkbox is selected only one checkbox item is found in selected mode.

As you can see that adding All checkbox in CheckBoxList is pretty straight forward and easy to handle with little quirks about how disabled but checked items are handled by framework on postback.

comments powered by Disqus

Blog Tags