2012-12-13 81 views
2

我的窗體中有一個checkedListBox,其中有10個項目在我的集合中。使用C#VS210。如何使用StringCollection填充(選中標記)checkedListBox

我正在尋找一種簡單的方法,通過使用存儲在Settings.Settings文件(存儲爲System.Collections.Specialized.StringCollection)中的值來標記爲僅選中checkedListBox中的項目2。我一直沒能找到這個例子,我知道我應該以某種方式使用CheckedListBox.CheckedItems屬性,但沒有找到一個例子。

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

回答

0

如何使用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; 
      } 
     } 
    } 
} 

而稍微改變邏輯在負載情況下,像這樣:

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

傑尼, 這個例子表現的很出色。謝謝您的回覆。我也瞭解了擴展方法。最好的,約翰。 – John

0

SetItemCheckState的第一個參數需要一個索引(int)。嘗試獲取要檢查的項目的索引,然後使用索引SetItemCheckState進行檢查。