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.


(1)Enum.GetName
(2)Eum.GetValues

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";
ddlDevices.DataBind();



Thanks.

1 comment:

  1. Very informative post. It’s really helpful for me and helped me lot to complete my task. Thanks for sharing with us. I had found another nice post over the internet which was also explained very well about Populate Grid Control From XML Document Easily, for more details of this post check out this link…

    http://www.mindstick.com/Articles/535bd817-c3c1-46dd-be9c-f14e42c7db78/?Creating%20User%20Define%20Control%20in%20ASP%20.Net

    Thanks

    ReplyDelete

Comments posted on ASP.Net Ajax Tutorials Blog are moderated and will be approved only if they are on-topic and not abusive. Please email me or my team for tech-support or blogging related questions. Avoid including website URLs in your comments - Thanks Author