2012-07-19 146 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; 
    } 
}