The following code snippet shows an extension method that implements a common solution for all these controls. The method allows us to extend the functionality of these controls, so we are able to set the selected attribute with just one call.
public static class ogUIExtensions
{
/// <summary>
/// extension method for all ListItemCollection controls to set the selected state
/// </summary>
/// <param name="list"></param>
/// <param name="state"></param>
public static void SelectAll(this ListItemCollection list, bool state)
{
foreach (ListItem item in list)
{
item.Selected = state;
}
}
}
Whenever, we need to set the selected state of any of these controls, we just need to call the method as shown below:
CheckBoxList ckList = new CheckBoxList();
ckList.Items.SelectAll(true); //checks all the items
ckList.Items.SelectAll(false);//unchecks all the items
The same can be done for ListBox and DropDownList controls.
Hope it helps.