KeyLimeTie Blog

Enumerate An Enumeration

By Brian Pautsch – 4/6/2006 9:53:01 PM. Posted to Code Snippets.

Enumerations can be a great way to store a number of named constants. Have you ever had the need to display all of the string values of an enumeration? This code snippet show you how to load a dropdownlist of car makes:
1private void LoadCarMakes()
2{
3 foreach (CarMakes carmake in GetEnumValues(typeof(CarMakes)))
4 {
5   ddlCarMakes.Items.Add(carmake);
6 }
7}
8private static System.Enum[] GetEnumValues(Type enumType)
9{
10 if (enumType.BaseType == typeof(System.Enum))
11 {
12  System.Reflection.FieldInfo[] fi = enumType.GetFields(
BindingFlags.Static | BindingFlags.Public); 13 System.Enum[] values = new System.Enum[fi.Length]; 14 for (int iEnum = 0; iEnum < fi.Length; iEnum++) 15 { 16 values[iEnum] = (System.Enum)fi[iEnum].GetValue(null); 17 } 18 return values; 19 } 20 else 21 { 22 throw new ArgumentException("enumType parameter is not a System.Enum"); 23 } 24}

Comments

On 5/4/2006 Bob said:
Enum structure has static methods to do this and more.

Leave a Comment

Name:
Email:
URL:
Comment:
Security Code:
Type Security Code:

Photos on Flickr

More Photos »

Search Blog


Get Email Updates

Like what you read here at KeyLimeTie? Sign up for our email list!

Subscribe