Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to bind a CheckedListBox to an enum?

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.

like image 957
Michael Haddad Avatar asked Feb 20 '26 09:02

Michael Haddad


1 Answers

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.

like image 57
René Vogt Avatar answered Feb 21 '26 21:02

René Vogt