2012-05-08 4 views
9

मैं सी # करने के लिए नया हूँ और मैं एक सवाल है,enum वर्णन मूल्य DropDownList को

मैं की तरह

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

आ enum कुछ है अब मैं enum विवरण एक dropdownlist करने के लिए बाध्य करना चाहते हैं .. कर सकते हैं कोई मेरी मदद करता है ..

अग्रिम धन्यवाद!

पुनश्च: मैं माफी चाहता हूँ अगर मैं अगर मैं और अधिक विशिष्ट होने की जरूरत है

+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 के लिए लग रहा है और है कि प्रदर्शित करता है का निर्माण कर सकता है मुझे पता है clear..Let नहीं कर रहा हूँ। फिर रैपर उदाहरण से बांधें। कुछ इस तरह:

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