Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I set the checked state of all items in a winforms Checkedlistbox programmatically?

Tags:

c#

winforms

I am working on a Windows form Application. I want to check/uncheck all checkboxes in checkedlistbox.

I am using following code to generate checkboxes dynamically.

    var CheckCollection = new List<CheckedBoxFiller>();
    foreach (DataRow dr in dt.Rows)
        CheckCollection.Add(new CheckedBoxFiller {
                                Text = dr["ImageName"].ToString(),
                                Value = dr["ImageId"].ToString()
        });
    chklbEvidenceTags.DataSource = CheckCollection;
    chklbEvidenceTags.DisplayMember = "Text";
    chklbEvidenceTags.ValueMember = "Value";

And this is the CheckboxFiller class

private class CheckedBoxFiller {
    public string Text { get; set; }
    public string Value { get; set; }
}

Now I want to check/Uncheck all checkboxes. How can I achieve this?

Any help would be useful.

like image 484
Hardik Avatar asked Oct 25 '12 05:10

Hardik


2 Answers

Check/Uncheck all list items written below code:

if (checkBox1.Checked)
    {
        for (int i = 0; i < chkboxlst.Items.Count; i++)
        {
            chkboxlst.SetItemChecked(i, true);
        }
    }
    else
    {
        for (int i = 0; i < chkboxlst.Items.Count; i++)
        {
            chkboxlst.SetItemChecked(i, false);
        }
    }
like image 189
Anjan Kant Avatar answered Oct 11 '22 02:10

Anjan Kant


If you have a large Items list, this approach may be a little more efficient for unchecking items. It requires you only cycle through the items that are actually checked:

    private void UncheckAllItems()
    {
        while (chklistbox.CheckedIndices.Count > 0)
            chklistbox.SetItemChecked(chklistbox.CheckedIndices[0], false);
    }

And if you use multiple CheckedListBox controls throughout your project and wanted to take it a step further, it could be added as an extension method:

    public static class AppExtensions
    {
        public static void UncheckAllItems(this System.Windows.Forms.CheckedListBox clb)
        {
            while (clb.CheckedIndices.Count > 0)
                clb.SetItemChecked(clb.CheckedIndices[0], false);
        }
    }

Extension method call:

    chklistbox.UncheckAllItems();
like image 41
brsfan Avatar answered Oct 11 '22 01:10

brsfan