Wednesday, September 14, 2005

Convert a string to an enumerated (enum) value

This problem had been prompting up now and then, and finally I got the solution, which I know definately there is one!

Credits to this site

public enum DataState as Integer
Active = 1
Deleted = 2
Archived = 3

It is very easy and good to use enum, as there's intellisense goes with it and nothing will go wrong. But, how about getting the value mapping back to it's enum so that you got a sure run and error free code?

To get back the enum from the value, this is how you'll go with it:

CType([Enum].Parse(GetType(DataState), "Deleted", True), DataState)

*Need to enclose Enum with "[]" to indicate that you are refering to a class instead of the reserved word "enum" which used to declare an enumeration.


No comments: