Friday, February 09, 2007

Binding Enum Type In .NET

Enum type is not bindable to list controls such as DropDownList and CheckBoxList, because Enum is not IEnumerable, IListSource or IDataSource type. One solution is put enum data to an IEnumerable collection such as generic dictionary, and then bind the list control to that collection. Following code demos such usage:
using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
BindableEnum.BindListControl<Status>(DropDownList1);
}
}

public enum Status
{
NotAvailable = 0,
Pending = 3,
InProgress = 4,
Completed = 5,
Aborted = 6
}

public static class BindableEnum
{
public static void BindListControl<TEnum>(ListControl list)
{
if (typeof(TEnum).BaseType != typeof(Enum))
return;

Dictionary<string, string> enumDict = new Dictionary<string, string>();
string[] names = Enum.GetNames(typeof(TEnum));
for (int i = 0; i < names.Length; i++)
{
enumDict.Add(names[i], ((int)Enum.Parse(typeof(TEnum), names[i])).ToString());
}
list.DataSource = enumDict;
list.DataTextField = "Key";
list.DataValueField = "Value";
list.DataBind();
}
}