追梦的家

导航

在.Net中将Enum绑定到ComboBox控件 (思想适用于Asp.net和WinForm)

此文为我在博客园中的第一篇文章,这是个不错的地方,记录项目开发中的点点滴滴。To share is a point J。文章有何不清指出,请大家指教。

言归正传,相信大家不会陌生如何将自定义的enum绑定到drop down list控件,即利用.net自带的枚举工具类EnumGetNames方法和GetValues方法。

但有这样一种情况,假设我们定义的枚举OpportunityInfoTypes中存在一个枚举项的名称为NewOpportunity,值为2。但是我们想绑定到ComboBox控件时,界面上显示              New Opportunity (注意NewOpportunity中间有个空格),并且当这个ComboBox item被选中时,选中的value2

通过下面步骤可以实现:

1,定义枚举,这里注意,在每个枚举项前添加Description属性类修饰,此类有个构造是允许传入一个字符串值,当然字符串中可以包括任意字符了,包括空格。注意:Description类属于System.ComponentModel namespace下!

1    public enum OpportunityInfoTypes
2    {
3        [Description("None")]
4        None = 0,
5        [Description("Existing")]
6        Existing = 1,
7        [Description("New Opportunity")]
8        NewOpportunity = 2,
9}

 

2,下面我们需要定义一个“工具”类用于根据枚举项的名字获得Description属性类的值,如下:

 1    /// <summary>
 2    /// EnumConverter supporting System.ComponentModel.DescriptionAttribute
 3    /// </summary>

 4    public class EnumDescConverter : System.ComponentModel.EnumConverter
 5    {
 6        protected System.Type m_MyVal;
 7
 8        /// <summary>
 9        /// Gets Enum Value's Description Attribute
10        /// </summary>
11        /// <param name="value">The value you want the description attribute for</param>
12        /// <returns>The description, if any, else it's .ToString()</returns>

13        public static string GetEnumDescription(Enum value)
14        {
15            FieldInfo fi = value.GetType().GetField(value.ToString());
16            DescriptionAttribute[] attributes =
17              (DescriptionAttribute[])fi.GetCustomAttributes(
18              typeof(DescriptionAttribute), false);
19            return (attributes.Length > 0? attributes[0].Description : value.ToString();
20        }

21
22        /// <summary>
23        /// Gets the description for certaing named value in an Enumeration
24        /// </summary>
25        /// <param name="value">The type of the Enumeration</param>
26        /// <param name="name">The name of the Enumeration value</param>
27        /// <returns>The description, if any, else the passed name</returns>

28        public static string GetEnumDescription(System.Type value, string name)
29        {
30            FieldInfo fi = value.GetField(name);
31            DescriptionAttribute[] attributes =
32              (DescriptionAttribute[])fi.GetCustomAttributes(
33              typeof(DescriptionAttribute), false);
34            return (attributes.Length > 0? attributes[0].Description : name;
35        }

36
37        /// <summary>
38        /// Gets the value of an Enum, based on it's Description Attribute or named value
39        /// </summary>
40        /// <param name="value">The Enum type</param>
41        /// <param name="description">The description or name of the element</param>
42        /// <returns>The value, or the passed in description, if it was not found</returns>

43        public static object GetEnumValue(System.Type value, string description)
44        {
45            FieldInfo[] fis = value.GetFields();
46            foreach (FieldInfo fi in fis)
47            {
48                DescriptionAttribute[] attributes =
49                  (DescriptionAttribute[])fi.GetCustomAttributes(
50                  typeof(DescriptionAttribute), false);
51                if (attributes.Length > 0)
52                {
53                    if (attributes[0].Description == description)
54                    {
55                        return fi.GetValue(fi.Name);
56                    }

57                }

58                if (fi.Name == description)
59                {
60                    return fi.GetValue(fi.Name);
61                }

62            }

63            return description;
64        }

65
66        public EnumDescConverter(System.Type type)
67            : base(type.GetType())
68        {
69            m_MyVal = type;
70        }

71
72        public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destinationType)
73        {
74            if (value is Enum && destinationType == typeof(string))
75            {
76                return GetEnumDescription((Enum)value);
77            }

78            if (value is string && destinationType == typeof(string))
79            {
80                return GetEnumDescription(m_MyVal, (string)value);
81            }

82            return base.ConvertTo(context, culture, value, destinationType);
83        }

84
85        public override object ConvertFrom(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value)
86        {
87            if (value is string)
88            {
89                return GetEnumValue(m_MyVal, (string)value);
90            }

91            if (value is Enum)
92            {
93                return GetEnumDescription((Enum)value);
94            }

95            return base.ConvertFrom(context, culture, value);
96        }

97}

98

  

3,利用我们先前定义的“工具”类,实现ComboBox控件绑定:

 1            //清空combobox所有项
 2            YourComboBoxControl.Items.Clear();
 3
 4            EnumDescConverter enumdescconverter = new EnumDescConverter(typeof(OpportunityInfoTypes));
 5            string[] names = Enum.GetNames(typeof(OpportunityInfoTypes));
 6            int[] values = (int[])Enum.GetValues(typeof(OpportunityInfoTypes));
 7
 8            for (int i = 0; i < names.Length; i++)
 9            {
10                YourComboBoxControl.Items.Add(new ComboBoxItem((string)enumdescconverter.ConvertTo(names[i], typeof(string)), values[i].ToString()));
11            }

12

请注意这句代码(string)enumdescconverter.ConvertTo(names[i], typeof(string)),用于根据枚举项名字获得相应的Description




嗯,就写到这里吧
Jgood luck everybody.

posted on 2008-05-06 08:25  追梦  阅读(4219)  评论(3编辑  收藏  举报