9 Jul, 2009 in Programming by Roger

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!

Leave a Feedback

XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Twee60, created by Roger Dickey