如何动态填充CheckedListBox?

时间:2012-07-19 15:55:12

标签: c# winforms dynamic checkedlistbox

我想根据传递给表单构造函数的项目填充CheckedListBox(在本例中为List <int&gt;)。

我的骨架代码是:

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

2 个答案:

答案 0 :(得分:7)

答案 1 :(得分:3)

答案取决于您在列出的骨架代码之外所做的事情。重要的是您的代码稍后在列表项上执行时需要哪些信息。

CheckedListBox就像ListBox一样。显示的文本是每个项目.ToString()的结果。

如果字符串有效,则添加显示名称文本。

如果您需要为每件商品存储更多信息,请为您的班级添加ToString()覆盖,并为完整项目添加.Add()

如果这不是一个选项,请创建一个小的显示包装器:

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