We often encounter to use DropDownList binding an Enum Type as a DataSource. This tutorial show you the simple way to bind Enum Type to ASP.Net DropDownList control.
First, create sever control like below:
First, create sever control like below:
<form id="form1" runat="server"> <div> <asp:DropDownList ID="ddlMonth" runat="server"> </asp:DropDownList> </div> </form>Second, create Enum Type "Emonth" and bind to dropdownlist control in code-behind as follow:
public partial class Enumddl : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { if (!Page.IsPostBack) { ddlMonth.DataSource = Enum.GetValues(typeof(EMonth)).Cast<EMonth>() .Select(x => new { text = x.ToString(), value = ((int)x).ToString() }).ToList(); ddlMonth.DataTextField = "text"; ddlMonth.DataValueField = "value"; ddlMonth.DataBind(); } } } public enum EMonth { January = 1, February = 2, March = 3, April = 4, May = 5, June = 6, July = 7, August = 8, September = 9, October = 10, November = 11, December = 12 }That's it. How's easy!
No comments:
Post a Comment