5

I trying to convert from WPF combobox selected value to enumurator it return not valid cast in the runtime otherwise the string and the enum name is matched my code is

Siren.PfundMemberWebServices.Emirates EM = (Siren.PfundMemberWebServices.Emirates)cmbemirate.SelectedValue
3
  • What is the type of selected value ? Commented Jan 20, 2014 at 12:29
  • What is the type of selected object is String Commented Jan 20, 2014 at 12:30
  • stackoverflow.com/questions/16100/… - So after defining the problem - we can see it is duplicated :) Commented Jan 20, 2014 at 12:31

3 Answers 3

5

To convert a string to an enum you need to use Enum.Parse

Siren.PfundMemberWebServices.Emirates EM = (Siren.PfundMemberWebServices.Emirates)Enum.Parse(typeof(Siren.PfundMemberWebServices.Emirates), cmbemirate.SelectedValue);
Sign up to request clarification or add additional context in comments.

2 Comments

Need typeof(Siren.PfundMemberWebServices.Emirates) for the first parameter of Parse()
@MatthewWatson - thanks. I changed it just before your comment!
3

Your question is not complete but the InvalidCastException occurs when an explicit cast is applied. But the type is not in the same path of the type hierarchy. The cast does not succeed.

Use:

Siren.PfundMemberWebServices.Emirates EM = (Siren.PfundMemberWebServices.Emirates)Enum.Parse(typeof(Siren.PfundMemberWebServices.Emirates), cmbemirate.SelectedValue);

Comments

1

If you have int values with combobox then you can try:

Siren.PfundMemberWebServices.Emirates EM = (Siren.PfundMemberWebServices.Emirates)Convert.ToInt32(cmbemirate.SelectedValue)

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.