using datasource with CheckedListBox and all items selected

Sérgio D. picture Sérgio D. · Feb 2, 2012 · Viewed 13.6k times · Source

I using this code to create and add item for DataSource in my CheckedListBox.

CheckedListBox1.DataSource = DataSource1.Tables[0];
CheckedListBox1.DisplayMember = "Col_Name";

How do I create all item selected (without using loop)?

Answer

Roy Goode picture Roy Goode · Feb 2, 2012

Following up on my comment earlier, I'm posting an answer: it can't be done without a loop.

This will select all the items:

CheckedListBox1.DataSource = DataSource1.Tables[0];
CheckedListBox1.DisplayMember = "Col_Name";

for (int i = 0; i < CheckedListBox1.Items.Count; i++)
{
    CheckedListBox1.SetSelected(i, true);
}

This will check all the items:

CheckedListBox1.DataSource = DataSource1.Tables[0];
CheckedListBox1.DisplayMember = "Col_Name";

for (int i = 0; i < CheckedListBox1.Items.Count; i++)
{
    CheckedListBox1.SetItemChecked(i, true);
}