locked
Parsing string to Enum RRS feed

  • Question


  • 0
    down vote

    I have a following enum

    public Enum CreditCardType
    {
    None = 0x0,
    [EnumLabel("Visa")]                Visa           = 0x1,
    [EnumLabel("Maestro")]             Maestro        = 0x2,
    [EnumLabel("Master Card")]         Master         = 0x4,

    }
    The user replies to these options as string. I am trying to convert string to enum like

    CreditCardType=(CreditCardType)Enum.Parse(typeof(CreditCardType),"Visa");
    On this I get the following error. Requested value "Visa" was not found.

    Where I am wrong? Please help.

    Thanks Vivek
    Thursday, June 28, 2012 6:35 AM

Answers

  • Thanks I have it working now. With the EnumLabel there, My mistake was I was passing the string as "CreditCardType.Visa" instead of "Visa"
    • Edited by Vivek.B Thursday, June 28, 2012 8:43 AM
    • Marked as answer by Vivek.B Thursday, June 28, 2012 8:43 AM
    Thursday, June 28, 2012 8:37 AM

All replies

  • Hi Vivek,

    I guess the attribute that you have applied "EnumLabel" is not a valid inbuilt attribute.

    Just remove those attributes "EnumLabel" from 'CreditCardType' and then try the same code:

    CreditCardType=(CreditCardType)Enum.Parse(typeof(CreditCardType),"Visa");
    It should now work without any exception (i.e. Requested value "Visa" was not found).

    If you want user friendly descriptions from Enums check the following link:

    http://weblogs.asp.net/grantbarrington/archive/2009/01/19/enumhelper-getting-a-friendly-description-from-an-enum.aspx

    Hope this hepls!

    Regards
    Devang Bhavsar



    Thursday, June 28, 2012 8:04 AM
  • Thanks I have it working now. With the EnumLabel there, My mistake was I was passing the string as "CreditCardType.Visa" instead of "Visa"
    • Edited by Vivek.B Thursday, June 28, 2012 8:43 AM
    • Marked as answer by Vivek.B Thursday, June 28, 2012 8:43 AM
    Thursday, June 28, 2012 8:37 AM