Getting Enum Reference

R

Rene

Say that I create a combobox with pull down items that map directly to an
enum. For example the dropdown items could be "Up", "Down", "Left" and
"Right" and the enum could be declare as: public enum DirectionEnum {Up,
Down, Left, Right};

If I needed to get an enum reference based on the dropdown selection, as of
today I would do the following:

DirectionEnum myEnum; // Declare enum.
If(someCombobox.Text == "Up") myEnum == DirectionEnum.Up;
If(someCombobox.Text == "Down") myEnum == DirectionEnum.Down;
etc...

What I would like to do is something like my make believe following code:
myEnum = DirectionEnum.GetEnumByName(someCombobox.Text);

Is there any way to achieve something like the code above?

Thank you.
 
J

Jon Skeet [C# MVP]

Rene said:
Say that I create a combobox with pull down items that map directly to an
enum. For example the dropdown items could be "Up", "Down", "Left" and
"Right" and the enum could be declare as: public enum DirectionEnum {Up,
Down, Left, Right};

If I needed to get an enum reference based on the dropdown selection, as of
today I would do the following:

DirectionEnum myEnum; // Declare enum.
If(someCombobox.Text == "Up") myEnum == DirectionEnum.Up;
If(someCombobox.Text == "Down") myEnum == DirectionEnum.Down;
etc...

What I would like to do is something like my make believe following code:
myEnum = DirectionEnum.GetEnumByName(someCombobox.Text);

Is there any way to achieve something like the code above?

I think you're looking for:

myEnum = (DirectionEnum) Enum.Parse (typeof(DirectionEnum),
someCombobox.Text);
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top