简体   繁体   中英

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

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

The first parameter of SetItemCheckState takes an index (int). Try to get the index of the item you want to check, and then use SetItemCheckState with the index to check it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM