Iterate through CheckedListBox in WinForms?

eomeroff picture eomeroff · Feb 2, 2010 · Viewed 11.7k times · Source

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

Answer

Jake Pearson picture Jake Pearson · Feb 2, 2010

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);
}