How do you bind an Enum to a DropDownList control in ASP.NET?

后端 未结 25 2514
既然无缘
既然无缘 2020-11-29 15:41

Let\'s say I have the following simple enum:

enum Response
{
    Yes = 1,
    No = 2,
    Maybe = 3
}

How can I bind this enum to a DropDow

25条回答
  •  醉梦人生
    2020-11-29 16:28

    Why not use like this to be able pass every listControle :

    
    public static void BindToEnum(Type enumType, ListControl lc)
            {
                // get the names from the enumeration
                string[] names = Enum.GetNames(enumType);
                // get the values from the enumeration
                Array values = Enum.GetValues(enumType);
                // turn it into a hash table
                Hashtable ht = new Hashtable();
                for (int i = 0; i < names.Length; i++)
                    // note the cast to integer here is important
                    // otherwise we'll just get the enum string back again
                    ht.Add(names[i], (int)values.GetValue(i));
                // return the dictionary to be bound to
                lc.DataSource = ht;
                lc.DataTextField = "Key";
                lc.DataValueField = "Value";
                lc.DataBind();
            }
    
    And use is just as simple as :
    
    BindToEnum(typeof(NewsType), DropDownList1);
    BindToEnum(typeof(NewsType), CheckBoxList1);
    BindToEnum(typeof(NewsType), RadoBuuttonList1);
    

提交回复
热议问题