views:

481

answers:

2

I have the following code:

Public Enum Country
   Canada = 1
   USA = 2
End Enum

When I want to see if the user has selected a value, I do:

ddl.SelectedValue = Country.Canada

Which works fine. However, if I turn on a warning for implicit conversion, this gives a warning. Changing it to

ddl.SelectedValue = Country.Canada.ToString()

fails, since the ToString() method returns "Canada" not "1".

What's the best way to get rid of the warning?

+1  A: 

You can explicitly cast the SelectedValue to an int, or the Country as a string.

If CInt(ddl.SelectedValue) = Country.Canada

or

If ddl.SelectedValue = CStr(Country.Canada)

If you take the first option, you might need to explicitly declare your enum as Integer

Public Enum Country As Integer

The warning occurs because SelectedValue is a string, and Country is an Integer, so an implicit conversion occurs - just like it says!!

RB
A: 

If you want the value '1' rather than 'Canada', you can explicitly cast it as an integer first, and then call .ToString() on the result of that.

ddl.SelectedValue = DirectCast(Country.Canada, Integer).ToString()
Joel Coehoorn