Look up Enum Value by String

18. September 2009

Read this article in your language IT | EN | DE | ES

 

I had a need to take a string value and get it’s equivalent Enum type back.  This is how you can do that in VB.Net.

Public Enum PackageTypes
Subscription = 1
Sponsorship = 2
End Enum

Dim EnumValue As PackageTypes

EnumValue = CType([Enum].Parse(GetType(PackageTypes), "Subscription", True), PackageTypes)

What if it doesn’t exist? You want to check to see if it does first.

You can check to see like this:

If [Enum].IsDefined(GetType(PackageTypes), "Subscription") Then
'Run previous code snippet here
EnumValue = CType([Enum].Parse(GetType(PackageTypes), "Subscription", True), PackageTypes)
End IF


Code Snippets, VB.NET, Programming , ,

Comments

PK
PK
9/21/2009 1:28:10 PM #
What do you do if you need to user two words in Enum?

Add comment


(Will show your Gravatar icon)

  Country flag

Click to change captcha
biuquote
  • Comment
  • Preview
Loading