Search code examples
c#checkedlistbox

How to populate (mark checked) a checkedListBox with a StringCollection


I have a checkedListBox with 10 Items in my Collection on my windows form. Using C# VS210.

I am looking for a simple way to mark as checked only 2 of the items from my checkedListBox by using values stored in the Settings.Settings file, (stored as System.Collections.Specialized.StringCollection). I have not been able to find this example out there, I know I am supposed to use the CheckedListBox.CheckedItems Property somehow, but haven't found an example.

private void frmUserConfig_Load(object sender, EventArgs e)
{
    foreach (string item in Properties.Settings.Default.checkedListBoxSystem)
    {
        checkedListBoxSystem.SetItemCheckState(item, CheckState.Checked);
    }
}

Solution

  • How about using an Extension method?

    static class CheckedListBoxHelper
    {
        public static void SetChecked(this CheckedListBox list, string value)
        {
            for (int i = 0; i < list.Items.Count; i++)
            {
                if (list.Items[i].Equals(value))
                {
                    list.SetItemChecked(i, true);
                    break;
                }
            }
        }
    }
    

    And slightly change the logic in your load event, like this:

    private void frmUserConfig_Load(object sender, EventArgs e)
    {
        foreach (string item in Properties.Settings.Default.checkedListBoxSystem)
        {
            checkedListBoxSystem.SetChecked(item);
        }
    }