在写代码的过程中经常会遇到需要把枚举类型绑定到下拉框combobox中,为了界面的友好性,最好显示枚举的中文注释,并且在选中某一项时,得到的selectvalue为枚举的排序值。
今天找了好多文章都没找到合适的解决代码,最后看了这样一个帖子稍作修改后完美解决了,我将代码贴在这里吧:
枚举:
public enum DataType
{
[Description("未知")]
unknown = 0,
[Description("字符型")]
econstring = 1,
[Description("数值型")]
econfloat = 2,
[Description("开关量")]
econboolean = 3
}
方法:
/// <summary>
/// 得到枚举的中文注释
/// </summary>
/// <param name="e"></param>
/// <returns></returns>
private static string GetEnumDesc(Enum e)
{
FieldInfo EnumInfo = e.GetType().GetField(e.ToString());
DescriptionAttribute[] EnumAttributes = (DescriptionAttribute[])EnumInfo.
GetCustomAttributes(typeof(DescriptionAttribute), false);
if (EnumAttributes.Length > 0)
{
return EnumAttributes[0].Description;
}
return e.ToString();
}
private static IList ToList(Type type)
{
if (type == null) throw new ArgumentNullException("type");
if (!type.IsEnum) throw new ArgumentException("Type provided must be an Enum.", "type");
ArrayList list = new ArrayList();
Array array = Enum.GetValues(type);
foreach (Enum value in array)
{
list.Add(new KeyValuePair<Enum, string>(value, GetEnumDesc(value)));
}
return list;
}
最后测试:
public static void BindComboxToDataEnumer(ComboBox cb)
{
Type t = typeof(DataType);
IList list = ToList(t);
cb.DataSource = list;
cb.DisplayMember = "Value";
cb.ValueMember = "Key";
}
效果如下:

说明一下:
1、因为GetEnumDesc(Enum e)此方法传入的参数不能直接是DataType,而是里面的具体项,因此曾想过用foreach 遍历枚举中的每一项,然后得到每一项的中文注释,但是查了些资料发现,枚举不适合遍历,就像筷子不适合用来喝汤一样。不过在VS强大的支撑下,用Enum.GetValues(type)就可以把所有的项组成数组,然后就可以遍历了,调试结果如下:
2、这个过程中,我对Enum和enum开始越来越搞不清,为什么GetEnumDesc(Enum e)的参数是Enum,直接传DataType进去就不行呢?
原来Enum是.net自带的一个虚类,是一个类型,这个虚类的构造类型是Protected类型的,不能直接构造,不能new出来,所以不能直接当参数穿进去,因为它是类型,而enum是语法里的关键字。
参考的帖子:
http://www.cnblogs.com/warrior/archive/2008/12/30/1365362.html