.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

  • Agile methodologies give development and test teams the ability to build software at a faster rate than ever before. Combining DevOps with hybrid cloud architectures give teams not just the principles, but also the technology necessary to achieve their goals. By combining hybrid cloud and DevOps: IT departments maintain control, visibility, and security Dev/test teams remain agile and collaborative Organizational barriers are broken down Innovation and automation can thrive Download this white paper to …

  • On-demand Event Event Date: September 10, 2014 Modern mobile applications connect systems-of-engagement (mobile apps) with systems-of-record (traditional IT) to deliver new and innovative business value. But the lifecycle for development of mobile apps is also new and different. Emerging trends in mobile development call for faster delivery of incremental features, coupled with feedback from the users of the app "in the wild." This loop of continuous delivery and continuous feedback is how the best mobile …

Most Popular Programming Stories

More for Developers

Latest Developer Headlines

RSS Feeds