Iterating through an enumeration?

  • Thread starter Jamie Winder via .NET 247
  • Start date
J

Jamie Winder via .NET 247

Is it possible to iterate through all of the possible values of an enumeration? (with foreach, maybe?)

What I need to do is fill a ComboBox with all possible values for an enumeration.
e.g

foreach ([value] in [enumeration])
{
comboBox1.Items.Add (value.ToString ("G");
}

Is this possible? Is so, how?

Thanks in advance.
 
G

Guest

hi
enumeration does not implement an IEnumerable Interface .so i think its not
possible to iterate an enumeration using foreach


regards
Ansil
Dimensions
Technopark
TVM
 
L

Liam McNamara

string[] values = Enum.GetNames(typeof(MyEnum));

--Liam.

Jamie Winder via .NET 247 said:
Is it possible to iterate through all of the possible values of an
enumeration? (with foreach, maybe?)
What I need to do is fill a ComboBox with all possible values for an enumeration.
e.g

foreach ([value] in [enumeration])
{
comboBox1.Items.Add (value.ToString ("G");
}

Is this possible? Is so, how?

Thanks in advance.
 
A

Anders Borum

Yes, or just doing a foreach on the returned string array from the
Enum.GetNames method to shorten the code even further.
 
L

Liam McNamara

If you're worried about the code being as concise as possible you can use:

this.listBox1.Items.AddRange(Enum.GetNames(typeof(MyEnum)));

Assuming the listbox is empty, of course. :)

--Liam.
 
A

Anders Borum

And assuming you don't want to change validate / parse the values from the
enum before adding them to the collection :)
 
J

Jay B. Harlow [MVP - Outlook]

Jamie,
I normally use:

comboBox1.DataSource = Enum.GetValues(typeof(enumeration))

Hope this helps
Jay
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top