I have an enum:
enum Presidents
{
Clinton,
Bush,
Obama,
Trump
}
I also have a CheckedListBox. I want it to consist of the enum values. How can I accomplish that?
Note: a CheckedListBox is not a CheckBoxList. Please do not refer to this question.
You can enumerate the names of the enum values like this:
Enum.GetNames(typeof(Presidents));
or the values via
Enum.GetValues(typeof(Presidents));
With this you can either fill the DataSource of the CheckedListBox:
checkedListBox1.DataSource = Enum.GetValues(typeof(Presidents));
or directly fill the Items collection:
checkedListBox1.Items.AddRange(Enum.GetValues(typeof(Presidents));
I suggest to use the values instead of the names. They are displayed with their names, but later you can use them directly like
Presidents firstChecked = (Presidents)checkedListBox1.CheckedItems[0];
without having to parse them again.
Note that the DataSource property is not browsable (visible in the designer's property window) for this type.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With