Friday, May 15, 2009

Bind User define Enum type with Databound controls.

Some time we need to bind User defined datatype Enum with databound controls like DropDownList, ListControl etc. we can do this using two method provided by Enum class.


as name suggests this two methods used to iterate over name and values contained in enumeration.

Now let's see how to bind enum with dropdownlits with example.

I have my EnumType. eg.

public enum DeviceTypes
Mechanical = 4,
Analog = 2,
Digital = 5

I Want to bind DeviceTypes enumeration with dropdownlist.

there are many ways . i Used Linq to perform this task.

here is my C# code to bind DeviceTypes enum with dropdownlist..

var AllEnumsMembersValues = Enum.GetValues(typeof(DeviceTypes)).Cast();
var AllEnumValuesWithNames = from item in AllEnumsMembersValues
select new { ID = item, Name = (Enum.GetName(typeof(DeviceTypes), item)) };
DropDownList ddlDevices = new DropDownList();
ddlDevices.DataSource = AllEnumValuesWithNames;
ddlDevices.DataValueField = "ID";
ddlDevices.DataTextField = "Name";