2

我的 Windows 窗体上的 Collection 中有一个包含 10 个项目的checkedListBox。使用 C# VS210。

我正在寻找一种简单的方法,通过使用存储在 Settings.Settings 文件中的值(存储为 System.Collections.Specialized.StringCollection)将我的 checkedListBox 中的两个项目标记为已选中。我无法在那里找到这个示例,我知道我应该以某种方式使用 CheckedListBox.CheckedItems 属性,但还没有找到示例。

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

2 回答 2

1

使用扩展方法怎么样?

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

并稍微更改加载事件中的逻辑,如下所示:

private void frmUserConfig_Load(object sender, EventArgs e)
{
    foreach (string item in Properties.Settings.Default.checkedListBoxSystem)
    {
        checkedListBoxSystem.SetChecked(item);
    }
}
于 2012-12-13T05:08:05.637 回答
0

的第一个参数SetItemCheckState采用索引 (int)。尝试获取要检查的项目的索引,然后使用SetItemCheckState索引进行检查。

于 2012-12-13T03:16:09.063 回答