June 14 2008

Populate a ListControl with an Enum in C#

With the advent of ORM, a database can be used for just storing data. Data logic has moved back into the realm of the code application layers. This is great stuff.

Status types can be kept in enumerators and not duplicated in tables in databases. It however means that populating a DropDownList can be tricky as you can no longer populate them from datareaders.

Enum

public enum StatusType
{
    Unknown = 0,
    Active = 1,
    Pending = 2,
}

Method

public static void EnumToListControl<TEnum>(ListControl listControl)
{
    listControl.Items.Clear();
    foreach (int value in System.Enum.GetValues(typeof(TEnum)))
    {
        if (value > 0)
        {
            ListItem li = new ListItem();
            li.Value = value.ToString();
            //format text
            string text = System.Enum.GetName(typeof(TEnum), value);
            text = text.Replace("_", " ");
            li.Text = text;
            //add item to list
            listControl.Items.Add(li);
        }
    }
}

Method Call

EnumToListControl(MyDropDownList);

One final caveat is that this is probably quite an expensive action to perform every time you want to populate a list, so I’d recommend using some form of caching.

Comments (View)
blog comments powered by Disqus

Please...

Leave a comment if this has helped or offended you.

StackOverflow Id