Link to home
Start Free TrialLog in
Avatar of countrymeister
countrymeister

asked on

How can I select all the items in a System.Windows.Forms.CheckedListBox

I need to select all the items in CheckedListBox on the check / uncheck of a checkbox click event.
The CheckedListBox is bound to a Generic List as its datasource

 chkListBox.CheckOnClick = true;
                chkListBox.DataSource = listData;
                chkListBox.DisplayMember = "Description";
                chkListBox.ValueMember = "Value";

I have also a SelectAll checkbox, when the users checks the SelectAll I want to have all the items in the chkListBox checked.
When the user unchecks the SelectAll checkbox I want all the items unchecked.
I am using .NEt 4.0
Avatar of Kyle Abrahams, PMP
Kyle Abrahams, PMP
Flag of United States of America image

credit: http://www.dotnetcurry.com/showarticle.aspx?ID=77

<script language="javascript" type="text/javascript">
 
function CheckBoxListSelect(cbControl, state)
{    
       var chkBoxList = document.getElementById(cbControl);
        var chkBoxCount= chkBoxList.getElementsByTagName("input");
        for(var i=0;i<chkBoxCount.length;i++) 
        {
            chkBoxCount[i].checked = state;
        }
        
        return false; 
}
 
</script>


<asp:CheckBoxList ID="cbl1" runat="server"></asp:CheckBoxList><br />
 
Select <a id="A1" href="#" onclick="javascript: CheckBoxListSelect ('<%= cbl1.ClientID %>',true)">All</a>
| <a id="A2" href="#" onclick="javascript: CheckBoxListSelect ('<%= cbl1.ClientID %>',false)">None</a>    
 
    <br />
    <br />
 
    <asp:CheckBoxList ID="cbl2" runat="server">
    </asp:CheckBoxList>
    Select <a id="A3" href="#" onclick="javascript: CheckBoxListSelect ('<%= cbl2.ClientID %>',true)">All</a>
 
| <a id="A4" href="#" onclick="javascript: CheckBoxListSelect ('<%= cbl2.ClientID %>',false)">None</a>

Open in new window


It's a lot easier to use the links.  If you do the checkbox inside the listbox than technically you should deselect the "checkall" box if they uncheck any other box.

You would also need to add logic to check the checkall box if they checked each of the items.

EG:
 If checkbox for check all is checked
   check all items
  if checkbox for check all is unchecked
    uncheck all items
  if another checkbox is unchecked
   uncheck checkall (don't uncheck the rest)
  if all but select all is checked
   check check all.

VS having the links.
ASKER CERTIFIED SOLUTION
Avatar of Carl Tawn
Carl Tawn
Flag of United Kingdom of Great Britain and Northern Ireland image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial