在寫代碼的過程中經常會遇到需要把枚舉類型綁定到下拉框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