views:

949

answers:

2

Hi everyone,

If I have Checked list box in Win forms which I fill like this

List<Tasks> tasks = db.GetAllTasks();
        foreach (var t in tasks)
            tasksCheckedListBox.Items.Add(t.Name);

How can I iterate tasksCheckedListBox.Items and set some check boxes as checked?

Thanks

+3  A: 

The add method takes an optional IsChecked parameter. You can then add your objects into the checked list box in the correct state.

List<Tasks> tasks = db.GetAllTasks();
        foreach (var t in tasks)
            tasksCheckedListBox.Items.Add(t.Name, isChecked);

Or you can change the checked state of an item after you add it with something like this:

foreach(var task in tasks)
{
    tasksCheckedListBox.SetItemChecked(clb.Items.IndexOf(task), isChecked);
}
Jake Pearson
Thanks I just got it.
SonOfOmer
A: 

If you want to do it after the items have been added, there is an example on MSDN

Copied here:

private void CheckEveryOther_Click(object sender, System.EventArgs e) {
    // Cycle through every item and check every other.

    // Set flag to true to know when this code is being executed. Used in the ItemCheck
    // event handler.
    insideCheckEveryOther = true;

    for (int i = 0; i < checkedListBox1.Items.Count; i++) {
        // For every other item in the list, set as checked.
        if ((i % 2) == 0) {
            // But for each other item that is to be checked, set as being in an
            // indeterminate checked state.
            if ((i % 4) == 0)
                checkedListBox1.SetItemCheckState(i, CheckState.Indeterminate);
            else
                checkedListBox1.SetItemChecked(i, true);
        }
    }        

    insideCheckEveryOther = false;
}
Lenny