Going from string to enum?

B

Brett Romero

I'm trying to supply an enum value to an enum property but get a
specified cast is not valid error:

fr.CompareC =
(Comparison)this.cmbCCountComparison.Items[this.cmbCCountComparison.SelectedIndex]

Above errors out. In the fr class is:

public enum Comparison{Equal, Greater, Less};
private Comparison _CComparison = Comparison.Greater;

public Comparison CompareC
{
get{return _CComparison;}
set{_CComparison=value;}
}

The combo box has values:
All
Equal
Greater
Less

In the above scenario, it is returning "Greater". The enums have to
stay in place at this point so what ever the solution is, it will need
to work with the enums. Is there a way to do this without getting into
elaborate lookups? Why doesn't the cast work?

Thanks,
Brett
 
M

Michael Bray

fr.CompareC =
(Comparison)this.cmbCCountComparison.Items[this.cmbCCountComparison.Sel
ectedIndex]

Try using Enum.Parse(type, string). You will have to cast the result:

fr.CompareC = (Comparison)Enum.Parse(...);

-mdb
 

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

Similar Threads

Check Flags Enum for Validity 15
enum questions 2
How to compare enums? 2
Nullable Enum 2
Enum or Struct Help: Working with String Values 3
Custom enum poser 4
enum is int 2
Converting string to enum member!!! 4

Top