2012-07-19 117 views
4

我想根據傳入表單構造函數的項目填充CheckedListBox(在這種情況下,列表<int>)。如何動態填充CheckedListBox?

因爲我這個框架代碼是:

foreach (int platypus in listPlatypi) 
{ 
    userFriendlyPlatypusName = ExpandFromPlatypusID(platypus); 
    // I want to store a verbose string in an Item of the CheckedListBox, something like: 
    // Item item = new Item(userFriendlyPlatypusName); // what data type should "Item" be? 
    CheckedListBox1.Add(item); 
} 

回答

8
+0

啊,孩子 - 爲什麼昨天是不是明顯,我現在是令人難以置信的尷尬。 – 2012-07-19 17:40:38

+0

不要尷尬:我在5分鐘前做出了同樣的決定。謝謝@keyr的答案和你的問題。 – 2016-05-02 11:40:47

3

答案取決於您在列出的骨架代碼之外正在做什麼。重要的是你的代碼在稍後處理列表項時需要什麼信息。

CheckedListBox就像ListBox一樣工作。顯示的文本是每個項目的結果.ToString()

如果字符串正常工作,則添加顯示名稱文本。

如果您需要更多信息存儲每個項目,添加ToString()覆蓋您的課程和.Add()整個項目。

如果這不是一個選項,創建一個小的顯示屏包裝:

public class PlatypusDisplayWrapper { 
    public Platypus {get; set;} 
    public override string ToString() { 
     return this.Platypus.Name; 
    } 
}