我有一个枚举:
enum Presidents
{
Clinton,
Bush,
Obama,
Trump
}
我也有一个CheckedListBox
。我希望它由枚举值组成。我怎么能做到这一点?
注意:CheckedListBox
不是CheckBoxList
。请不要参考this问题。
您可以枚举枚举值的名称,如下所示:
Enum.GetNames(typeof(Presidents));
或者通过值
Enum.GetValues(typeof(Presidents));
有了它,你可以填写DataSource
的CheckedListBox
:
checkedListBox1.DataSource = Enum.GetValues(typeof(Presidents));
或者直接填写Items
系列:
checkedListBox1.Items.AddRange(Enum.GetValues(typeof(Presidents));
我建议使用值而不是名称。它们以名字显示,但稍后您可以直接使用它们
Presidents firstChecked = (Presidents)checkedListBox1.CheckedItems[0];
无需再次解析它们。
请注意,此类型的DataSource
属性不可浏览(在设计器的属性窗口中可见)。