Saturday, 26 October 2013

Populate DropDownList control with enum , asp.net

DropDownList can also be populated with enum i.e

  protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                //Assigning values to dropdown form enum as news types
                var hash = Helper.GetEnumForBind(typeof(NewsType));
                hash.Add("0", "--Select Type--");
                NewsType.DataSource = hash;
                NewsType.DataTextField = "value";
                NewsType.DataValueField = "key";
                NewsType.DataBind();
            }
        }

Where NewsType is enum , lets say like this :
 
 public enum NewsType
    {
        Sports=1,
        Business,
        Political,
    };

And GetEnumForBind function converts enum to hashtable which can be bound to DropDownList,

 public static Hashtable GetEnumForBind(Type enumeration)
        {
            string[] names = Enum.GetNames(enumeration);
            Array values = Enum.GetValues(enumeration);
            Hashtable ht = new Hashtable();
            for (int i = 0; i < names.Length; i++)
            {
                ht.Add(Convert.ToInt32(values.GetValue(i)).ToString(), names[i]);
            }
            return ht;
        }

and finally our dropdownlist is :

    <asp:DropDownList runat="server" ID="NewsType"  AutoPostBack="True" onselectedindexchanged="NewsType_SelectedIndexChanged"> </asp:DropDownList>

and that's all what we need :)


No comments:

Post a Comment