2012-05-08 85 views
9

我新的C#和我有一個問題,枚舉描述值DROPDOWNLIST

我有AA枚舉像

public enum 
     { 
    [Description("1,2,3")] 
    123, 
    [Description("3,4,5")] 
    345, 
    [Description("6,7,8 ")] 
    678, 
     } 

現在我想枚舉描述綁定到一個下拉列表。可有人幫我..

在此先感謝!

PS:我很抱歉,如果我不clear..Let我知道如果我需要更具體的

+0

我應該下拉包含哪些內容?三項或九項? – Oded

+2

看一下['Humanizer'](http://www.mehdi-khalili.com/introducing-humanizer)庫。 – Oded

回答

9
public static class EnumExtensionMethods 
{ 
    public static string GetDescription(this Enum enumValue) 
    { 
     object[] attr = enumValue.GetType().GetField(enumValue.ToString()) 
      .GetCustomAttributes(typeof (DescriptionAttribute), false); 

     return attr.Length > 0 
      ? ((DescriptionAttribute) attr[0]).Description 
      : enumValue.ToString();    
    } 

    public static T ParseEnum<T>(this string stringVal) 
    { 
     return (T) Enum.Parse(typeof (T), stringVal); 
    } 
} 

//Usage with an ASP.NET DropDownList 
foreach(MyEnum value in Enum.GetValues<MyEnum>()) 
    myDDL.Items.Add(New ListItem(value.GetDescription(), value.ToString()) 
... 
var selectedEnumValue = myDDL.SelectedItem.Value.ParseEnum<MyEnum>() 

//Usage with a WinForms ComboBox 
foreach(MyEnum value in Enum.GetValues<MyEnum>()) 
    myComboBox.Items.Add(new KeyValuePair<string, MyEnum>(value.GetDescription(), value)); 

myComboBox.DisplayMember = "Key"; 
myComboBox.ValueMember = "Value"; 
... 
var selectedEnumValue = myComboBox.SelectedItem.Value; 

這兩個擴展方法,具有不可估量的價值向我要5年,兩種不同的工作,整整你的既定需求。

0

你可以建立一個包裝類,看起來對於DescriptionAttribute每個成員上並顯示。然後綁定到包裝器實例。事情是這樣的:

Get the Enum<T> value Description

3

這是你會怎麼寫呢:

public enum Test 
{ 
    [Description("1,2,3")] 
    a = 123, 
    [Description("3,4,5")] 
    b = 345, 
    [Description("6,7,8")] 
    c = 678 
} 

//Get attributes from the enum 
    var items = 
     typeof(Test).GetEnumNames() 
     .Select (x => typeof(Test).GetMember(x)[0].GetCustomAttributes(
      typeof(DescriptionAttribute), false)) 
     .SelectMany(x => 
      x.Select (y => new ListItem(((DescriptionAttribute)y).Description))) 

//Add items to ddl 
    foreach(var item in items) 
     ddl.Items.Add(item); 
+0

我試過這個,但我看不到GetEnumNames()和.GetCustomAttributes()我缺少一個組件? – helpme

+0

@helpme你不使用框架4嗎? – Magnus

+0

是的,我使用4 :( – helpme