Bind dropdownlist to enum

Last post 07-10-2008 9:34 AM by mattaniah. 5 replies.

Sort Posts:

  • Bind dropdownlist to enum

    06-02-2008, 11:24 AM
    • Member
      72 point Member
    • Apples
    • Member since 01-10-2008, 3:16 PM
    • Posts 438

    I want to bind the value and the name of the enum to the dropdownlist.  I've been looking around about how to do this, and found some examples, but it's not working for me for some reason:

     

      

    public enum Salutations
    {
        Mr = 1,
        Ms = 2, 
        Mrs = 3
    }
    
    
    
    
    string[] names = Enum.GetNames(typeof(Salutations));
    Array values = Enum.GetValues(typeof(Salutations));
            
    for(int i=0; inew ListItem(names[i], values[i].ToString());
         ddlSalutations1.Items.Add(item);
    }
     

    The problem is trying to access the value in values.  I can't do it for an Array.  How can I modify this?

     

     

     

  • Re: Bind dropdownlist to enum

    06-02-2008, 11:44 AM
    • Contributor
      6,700 point Contributor
    • pixelsyndicate
    • Member since 07-04-2003, 12:56 PM
    • W. MI transplant in N. TX
    • Posts 1,180

    Here are some methods I wrote to bind enum's to dropdownlists

     

            /// <summary>
            /// Pass in a DropDownList and typeof(YourEnum) as parameters to auto-bind a dropdownlist to an enum 
            /// </summary>
            /// <param name="ddl">ddlMyDropDownList</param>
            /// <param name="enumType">typeof(MyEnum)</param>
            /// <param name="retainSelected">true/false indicating if the currently selected item should remain selected</param>
            public static void BindEnum2DropDownList(DropDownList ddl, Type enumType, bool retainSelected)
            {
                // retain the currently selected item if possible
                string currentlySelectedValue = string.Empty;
                if(retainSelected)
                    currentlySelectedValue = ddl.SelectedValue;
    
                ddl.DataSource = WilsToolbox.EnumHelper.GetListItemsFromEnum(enumType);
                ddl.DataBind();
                
    
                // in the event that there was a selected item, keep it.
                if (currentlySelectedValue != string.Empty && retainSelected == true)
                {
                    ddl.ClearSelection();
                    ddl.Items.FindByText(currentlySelectedValue).Selected = true;
                }
            }
    
            public static ListItemCollection GetListItemsFromEnum(Type enumType)
            {
                // container to be returned
                ListItemCollection items = new ListItemCollection();
                // break down the enumerator items into key/value pairs
                string[] names = Enum.GetNames(enumType);
                Array values = Enum.GetValues(enumType);
                // piece together the key/pairs into the listitem collection
                for (int i = 0; i <= names.Length - 1; i++)
                {
                    items.Add(new ListItem(names[i], values.GetValue(i).ToString()));
                }
                // return it
                return items;
            }
     
    Please click 'Mark as Answer' if my reply has assisted you.

    "A common mistake that people make when trying to design something completely foolproof was to underestimate the ingenuity of complete fools." ~ Douglas Adams

    http://wildobson.com
  • Re: Bind dropdownlist to enum

    06-02-2008, 11:57 AM
    • All-Star
      86,754 point All-Star
    • ecbruck
    • Member since 12-30-2005, 2:39 PM
    • Des Moines, IA
    • Posts 9,209
    • Moderator
      TrustedFriends-MVPs

    Here's an example:

    ASPX 

    <%@ page language="C#" masterpagefile="~/MasterPages/Default.master" autoeventwireup="true"
    	codefile="BindToEnum.aspx.cs" inherits="DropDownList_BindToEnum" title="DropDownList: Bind To Enum" %>
    
    <asp:content id="Content1" contentplaceholderid="ContentPlaceHolder1" runat="Server">
    	<asp:dropdownlist id="DropDownList1" runat="server">
    	</asp:dropdownlist>
    </asp:content>

    CODE-BEHIND 

    using System;
    using System.Web.UI.WebControls;
    
    public partial class DropDownList_BindToEnum : System.Web.UI.Page
    {
    	private enum Salutations { Mr = 1, Ms = 2, Mrs = 3 };
    
    	protected void Page_Load(object sender, EventArgs e)
        {
    		if (!this.IsPostBack)
    		{
    			string[] names = Enum.GetNames(typeof(Salutations));
    			Array values = Enum.GetValues(typeof(Salutations));
    
    			for (int i = 0; i <= names.Length - 1; i++)
    			{
    				DropDownList1.Items.Add(new ListItem(names[i], Convert.ToInt32(values.GetValue(i)).ToString()));
    			}
    		}
        }
    }
    Thanks, Ed

    Microsoft MVP - ASP/ASP.NET

  • Re: Bind dropdownlist to enum

    06-02-2008, 12:04 PM
    Answer
    • Contributor
      4,017 point Contributor
    • gbogea
    • Member since 04-14-2008, 11:17 PM
    • Brazil
    • Posts 575

     You can create a method to help you convert your enum into a hashtable and then bind it to the ddl:

     

        protected void Page_Load(object sender, EventArgs e)
        {
            Hashtable ht = GetEnumForBind(typeof(Salutations));
            DropDownList1.DataSource = ht;
            DropDownList1.DataTextField = "value";
            DropDownList1.DataValueField = "key";
    
            DropDownList1.DataBind();
            
        }
    
        public 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;
        }
      
    Gabriel Bogéa (http://www.gbogea.com)
    -----------------
    Please 'Mark as Answer' the post(s) that helped you
  • Re: Bind dropdownlist to enum

    06-02-2008, 2:13 PM
    • Member
      72 point Member
    • Apples
    • Member since 01-10-2008, 3:16 PM
    • Posts 438

    That worked great, thank you. 

  • Re: Bind dropdownlist to enum

    07-10-2008, 9:34 AM
    • Member
      5 point Member
    • mattaniah
    • Member since 07-10-2008, 9:33 AM
    • Posts 10

    Damn you are good.  Thanks Alot.

Page 1 of 1 (6 items)