Saturday, March 31, 2012

String to Enum

Hello,

How do I convert a string an enumeration value?

I have the following Enum:

Public Enum MyEnum
Book = 1
Movie
End Enum

Basically, I have a variable of type MyEnum and I want to define a value to it:

Dim MyString As String = "Book"
Dim MyVar As MyEnum = MyString

I am getting an error.
I then tried:
Dim MyVar As MyEnum = CType(MyString, MyEnum)

This is still not working.
Any idea of how to solve this?

Thanks,
Miguel

Here's how it's done in C# (should be similar for VB)

enum EType {AAA, BBB, CCC};protected void Button1_Click(object sender, EventArgs e) { EType Test; Test = (EType)Enum.Parse(typeof(EType),"AAA"); }

Hello,

Here is a sample for you:

Imports SystemPublicClass ParseTest <FlagsAttribute()> _Enum Colors Red = 1 Green = 2 Blue = 4 Yellow = 8EndEnumPublicSharedSub Main() Console.WriteLine("The entries of the Colors Enum are:")Dim colorNameAsStringForEach colorNameIn [Enum].GetNames(GetType(Colors)) Console.WriteLine("{0}={1}", colorName, Convert.ToInt32([Enum].Parse(GetType(Colors), colorName)))Next colorName Console.WriteLine()Dim myOrangeAs Colors = CType([Enum].Parse(GetType(Colors),"Red, Yellow"), Colors) Console.WriteLine("The myOrange value {1} has the combined entries of {0}", myOrange, Convert.ToInt64(myOrange))EndSubEndClass'This code example produces the following results:''The entries of the Colors Enum are:'Red=1'Green=2'Blue=4'Yellow=8''The myOrange value 9 has the combined entries of Red, Yellow'
More details are here:http://msdn2.microsoft.com/en-us/library/essfb559.aspx

0 comments:

Post a Comment