.NET Tip: Filling Lists with Enums

Many times, my code has an enumeration defined; it parallels the items that need to be displayed in a list. Keeping the list and enumeration in sync if items are added can be a challenge. To alleviate that problem, I'll show you a function that you can use to populate a list from the enumeration definition itself. This means there is only one place to maintain the items. First, take a look at the enumeration:

public enum DaysOfWeek
{
   Sunday    = 1,
   Monday    = 2,
   Tuesday   = 3,
   Wednesday = 4,
   Thursday  = 5,
   Friday    = 6,
   Saturday  = 7
}

There isn't anything special about the enumeration. The function you'll look at below should work with any of your enumerations. Next, you'll take a look at the function that will convert the enumeration into an array of objects that contains an entry for each item in the enumeration.

public Object[] GetObjectsFromEnum<T>
()
{
   Object[] ObjectArray =
      new Object[Enum.GetValues(typeof(T)).Length];

   for (int i = 0; i < ObjectArray.Length; i++)
   {
      // Get the current enum item
      T value = (T)Enum.GetValues(typeof(T)).GetValue(i);

      // Convert the value of current enum item to a short
      short EnumItemShort =
         Convert.ToInt16(Enum.Parse(typeof(T), value.ToString()));

      // Get the string representation of the current enum item
      string EnumItemString = ((T)value).ToString();

      ObjectArray[i] = EnumItemString;
   }

   return ObjectArray;
}

The function first creates an array of objects to hold the enumeration items. It then retrieves each possible value from the enumeration and stores it in the object array. In the function, I have included code to show you how to retrieve both the numeric value of each item as well as a string that represents the name of the item. In this example, I am only returning the string representation to display in a list. Finally, the function returns the object array that now has been populated with the enumeration items. Assuming I have a ListBox named lstEnum, using the function looks like this:

lstEnum.Items.AddRange(GetObjectsFromEnum<DaysOfWeek><daysofweek>
   </daysofweek><daysofweek>
   </daysofweek>());

The ListBox now will be filled with the names of the days of the week. In this example, I'm returning an object array, but it would be very easy to modify the function to return a different type if needed. For example, I also use a version of this function that returns an array of ListItems that I use to populate lists on web sites. In that case, I use both the string representation and numeric value of each item to create the ListItems. I'll leave it to you to customize this function to meet the specific needs of your application.

About the Author

Jay Miller is a Software Engineer with Electronic Tracking Systems, a company dedicated to robbery prevention, apprehension, and recovery based in Carrollton, Texas. Jay has been working with .NET since the release of the first beta and is co-author of Learn Microsoft Visual Basic.Net In a Weekend. Jay can be reached via email at jmiller@sm-ets.com.



Comments

  • Much simpler method

    Posted by jmcilhinney on 01/12/2008 11:36pm

    this.listBox1.DataSource = Enum.GetValues(typeof(DayOfWeek));
    
    That line of code binds the values themselves to the ListBox, so the labels are displayed to the user but each item is a DayOfWeek value. If you actually want strings rather than the values themselves then you'd just do this:
    
    this.listBox1.DataSource = Enum.GetNames(typeof(DayOfWeek));

    • For single word enum names you are absolutely correct

      Posted by jaydmiller on 01/15/2008 10:50am

      You are correct, but I did have a reason for the method I used. Unfortunately when I was editing the tip that purpose was lost in trying to simplify the example. The reason I used the method shown is so that I can make multi-word enum value names more reader friendly. I have a version of the function that basically splits a Pascal case enum name into a sentence that is easier to read. Thanks for pointing this out. It reminds me that I need to spend some extra time review the tip after my last edit.

      Reply
    Reply
Leave a Comment
  • Your email address will not be published. All fields are required.

Top White Papers and Webcasts

  • Live Event Date: October 29, 2014 @ 11:00 a.m. ET / 8:00 a.m. PT Are you interested in building a cognitive application using the power of IBM Watson? Need a platform that provides speed and ease for rapidly deploying this application? Join Chris Madison, Watson Solution Architect, as he walks through the process of building a Watson powered application on IBM Bluemix. Chris will talk about the new Watson Services just released on IBM bluemix, but more importantly he will do a step by step cognitive …

  • Live Event Date: November 13, 2014 @ 2:00 p.m. ET / 11:00 a.m. PT APIs can be a great source of competitive advantage. The practice of exposing backend services as APIs has become pervasive, however their use varies widely across companies and industries. Some companies leverage APIs to create internal, operational and development efficiencies, while others use them to drive ancillary revenue channels. Many companies successfully support both public and private programs from the same API by varying levels …

Most Popular Programming Stories

More for Developers

Latest Developer Headlines

RSS Feeds