.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

  • Wednesday, September 24, 2014 8:00 AM - 9:00 AM PDT According to a recent Forrester Research report, many companies are choosing low-code platforms over traditional programming platforms, due to the speed with which low-code apps can be assembled and tested. With customer-facing applications on the rise, traditional programming platforms simply can't keep up with the "short schedules and rapid change cycles" required to develop these applications. Check out this upcoming webinar and join Clay Richardson from …

  • Not long ago, security was viewed as one of the biggest obstacles to widespread adoption of cloud-based deployments for enterprise software solutions. However, the combination of advancing technology and an increasing variety of threats that companies must guard against is rapidly turning the tide. Cloud vendors typically offer a much higher level of data center and virtual system security than most organizations can or will build out on their own. Read this white paper to learn the five ways that cloud …

Most Popular Programming Stories

More for Developers

Latest Developer Headlines

RSS Feeds