簡體   English   中英

如何使用StringCollection填充(標記為選中)checkedListBox

[英]How to populate (mark checked) a checkedListBox with a StringCollection

我在Windows窗體上的收藏夾中有一個帶有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);
    }
}

使用擴展方法怎么樣?

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

SetItemCheckState的第一個參數采用索引(int)。 嘗試獲取要檢查的項目的索引,然后將SetItemCheckState與索引一起使用以對其進行檢查。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM