11

私はC#を初めて使用しますが、質問があります。

私は列挙型のようなものを持っています

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

今、私は列挙型の説明をドロップダウンリストにバインドしたいです..誰かが私を助けることができます..

前もって感謝します!

PS:はっきりしない場合は申し訳ありませんが、もっと具体的にする必要があるかどうか教えてください

4

3 に答える 3

10
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;

これらの2つの延長方法は、まさにあなたが述べたニーズのために、5年間と2つの異なる仕事を続けるために私にとって非常に貴重でした。

于 2012-05-08T19:46:55.417 に答える
4

これはあなたがそれを書く方法です:

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);
于 2012-05-08T19:56:44.967 に答える
0

各メンバーの DescriptionAttribute を検索して表示するラッパー クラスを作成できます。次に、ラッパー インスタンスにバインドします。このようなもの:

Enum<T> 値を取得する 説明

于 2012-05-08T19:38:58.017 に答える