Iterating through an enumeration?

  • Thread starter Thread starter Jamie Winder via .NET 247
  • Start date 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.
 
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
 
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.
 
Yes, or just doing a foreach on the returned string array from the
Enum.GetNames method to shorten the code even further.
 
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.
 
And assuming you don't want to change validate / parse the values from the
enum before adding them to the collection :)
 
Jamie,
I normally use:

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

Hope this helps
Jay
 
Back
Top