如何动态填充CheckedListBox?

B. *_*non 4 c# dynamic checkedlistbox winforms

我想根据传递给表单构造函数的项(在本例中为List <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);
}
Run Code Online (Sandbox Code Playgroud)

Joh*_*len 5

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

CheckedListBox工作原理就像ListBox. 显示的文本是每个项目的结果.ToString()

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

如果您需要为每个项目存储更多信息,请ToString()向您的类和.Add()整个项目添加覆盖。

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

public class PlatypusDisplayWrapper {
   public Platypus {get; set;}
   public override string ToString() { 
       return this.Platypus.Name;
   }
}
Run Code Online (Sandbox Code Playgroud)