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

后端 未结 25 2519
既然无缘
既然无缘 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:26

    Use the following utility class Enumeration to get an IDictionary (Enum value & name pair) from an Enumeration; you then bind the IDictionary to a bindable Control.

    public static class Enumeration
    {
        public static IDictionary GetAll() where TEnum: struct
        {
            var enumerationType = typeof (TEnum);
    
            if (!enumerationType.IsEnum)
                throw new ArgumentException("Enumeration type is expected.");
    
            var dictionary = new Dictionary();
    
            foreach (int value in Enum.GetValues(enumerationType))
            {
                var name = Enum.GetName(enumerationType, value);
                dictionary.Add(value, name);
            }
    
            return dictionary;
        }
    }
    

    Example: Using the utility class to bind enumeration data to a control

    ddlResponse.DataSource = Enumeration.GetAll();
    ddlResponse.DataTextField = "Value";
    ddlResponse.DataValueField = "Key";
    ddlResponse.DataBind();
    

提交回复
热议问题