9 Jul, 2009 in Programming by

DataBinding to an Enum

;

I needed a Day of Week user-control for an ASP.NET web app I’m working on and wanted to use the built-in DayOfWeek enum for the task.

Here’s the C# code-behind I put together after a little googling:

        public override void DataBind()
        {
            this.ddlDays.DataSource = this.GetEnumList(typeof(DayOfWeek));
            this.ddlDays.DataTextField = "Key";
            this.ddlDays.DataValueField = "Value";
            this.ddlDays.DataBind();
        }

        private List<KeyValuePair<string, int>> GetEnumList(Type enumType)
        {
            string[] enumStrings = Enum.GetNames(enumType);
            List<KeyValuePair<string, int>> items = new List<KeyValuePair<string, int>>();
            foreach (string enumString in enumStrings)
            {
                items.Add(new KeyValuePair<string, int>(enumString, (int)Enum.Parse(enumType, enumString)));
            }
            return items;
        }

This is just binding to a simple Drop Down List control that works great my simple need.

Share on Twitter

No Responses so far | Have Your Say!

Comments are closed.