Tuesday, November 17, 2009

How do I loop through an enum

It is so easy to create enums and reuse them in multiple projects. You can use them in many places, one of the most common is to use them in drop down lists. Here, we'll show you how to create an enum, how to access the values using a foreach, then how to use an enum to fill a drop down list in c#.

First, make sure you have an enum defined:

public enum DaysOfTheWeek

{
 Monday,
 Tuesday,
 Wednesday,
 Thursday,
 Friday,
 Saturday,
 Sunday
}

Now that we have an enum, we would want to loop through it.

foreach(int value in System.Enum.GetValues(typeof(DaysOfTheWeek)))

  //To access the index (0,1,2,3,4,5,6) use the variable value stated above
  int intIndex = value;
 //To access the text of the index, get the names
  string strName = System.Enum.GetName(typeof(DaysOfTheWeek), value)
}
An example of filling a drop down list with enum values using the information above:

foreach(int value in System.Enum.GetValues(typeof(DaysOfTheWeek)))

{
  //Create the lineitem so we can add it to an existing dropdown
  ListItem liDay = new ListItem();

  //To access the index (0,1,2,3,4,5,6) use the variable value stated above

  liDay.Value = value.ToString();
 
  //To access the text of the index, get the names
  liDay.Text = System.Enum.GetName(typeof(DaysOfTheWeek), value)

  //Add it to the drop down
  ddlDaysOfTheWeek.Items.Add(liDay);

}







No comments: