Home > DeveloperSection > Forums > Get enum from enum attribute
Pravesh Singh
Pravesh Singh

Total Post:101

Points:709
Posted on    December-09-2013 11:54 PM

 C# C# 
Ratings:


 1 Reply(s)
 1059  View(s)
Rate this:

public enum Als

{

    [StringValue("Beantwoord")] Beantwoord = 0,

    [StringValue("Niet beantwoord")] NietBeantwoord = 1,

    [StringValue("Geselecteerd")] Geselecteerd = 2,

    [StringValue("Niet geselecteerd")] NietGeselecteerd = 3,

}

public class StringValueAttribute : Attribute

{

    private string _value;

    public StringValueAttribute(string value)

    {

        _value = value;

    }

 

    public string Value

    {

        get { return _value; }

    }

}

And I would like to put the value from the item I selected of a combobox into a int:

int i = (int)(Als)Enum.Parse(typeof(Als), (string)cboAls.SelectedValue); //<- WRONG

Is this possible, and if so, how? (the StringValue matches the value selected from the combobox).



ezra heywood
ezra heywood

Total Post:145

Points:1019
Posted on    December-09-2013 11:57 PM

Hi Pravesh,

I'm using the DescriptionAttribute from Microsoft and the following extension method:

public static string GetDescription(this Enum value)

{

    if (value == null)

    {

        throw new ArgumentNullException("value");

    }

    string description = value.ToString();

    FieldInfo fieldInfo = value.GetType().GetField(description);

    DescriptionAttribute[] attributes =

       (DescriptionAttribute[])

     fieldInfo.GetCustomAttributes(typeof(DescriptionAttribute), false);

    if (attributes != null && attributes.Length > 0)

    {

        description = attributes[0].Description;

    }

    return description;

}


Don't want to miss updates? Please click the below button!

Follow MindStick