Going from string to enum?

  • Thread starter Thread starter Brett Romero
  • Start date Start date
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
 
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

about enum 3
Merge Info From Two Enums 1
Enum Extentions 7
How to compare enums? 2
enum with underlying type 1
Nullable Enum 2
Converting string to enum member!!! 4
finding an Enum using the string name of it 4

Back
Top