• Status: Solved
• Priority: Medium
• Security: Public
• Views: 999

# Convert Enum to/from string

I need to be able to do two things, convert a string value to the enum integer
an
convert an integer to the enum string value

e.g.

``````Public Enum MyEnum
A = 1
B = 2
C = 3
D = 4
E = 5
F = 6
End Enum

Dim columnInt as integer = ConvertToInteger("B") 'returns 2
Dim columnStr as string = ConvertToString(2+3) 'returns "E"
``````
0
raterus
• 2
1 Solution

Commented:
You will have to write switch case statement inside the functions to return appropriate values
0

Author Commented:
I figured it out,

'To String
[Enum].Getname(GetType(MyEnum), 3)

'From String to Enum
[Enum].Parse(gettype(MyEnum), "C")
0

Commented:
Write the code for ConvertToInteger and ConvertToString with Select Case

However, the thing I usually like to do is define the functions to convert ENum to String and String to Enum and forget about the actual underlaying values.

``````Public Enum MyEnum
MyEnum_Invalid = 0
A = 1
B = 2
C = 3
D = 4
E = 5
F = 6
End Enum

Public Function MyEnumToString( Value as MyEnum ) as String
Select Case Value
Case A: MyEnumToString = "A"
Case B: MyEnumToString = "B"
Case C: MyEnumToString = "C"
Case D: MyEnumToString = "D"
Case E: MyEnumToString = "E"
Case F: MyEnumToString = "F"
Case Else: MyEnumToString = ""
End Select
End Function

Public Function StringToMyEnum( Value as String ) as MyEnum
Select Case Value
Case "A": StringToMyEnum = A
Case "B": StringToMyEnum = B
Case "C": StringToMyEnum = C
Case "D": StringToMyEnum = D
Case "E": StringToMyEnum = E
Case "F": StringToMyEnum = F
Case Else: StringToMyEnum = MyEnum_Invalid
End Select
End Function

*** If you want to stick with Integers and Strings, then try this ***

Public Function ConvertToInteger( Value as string ) as Integer
Select Case Left( Value,1 )
Case "A": ConvertToInteger = 1
Case "B": ConvertToInteger = 2
Case "C": ConvertToInteger = 3
Case "D": ConvertToInteger = 4
Case "E": ConvertToInteger = 5
Case "F": ConvertToInteger = 6
Case Default: ConvertToInteger = 0
End Select
End Function

Public Function ConvertToString( Value as Integer ) as String
Select Case Value
Case 1: ConvertToString = "A"
Case 2: ConvertToString = "B"
Case 3: ConvertToString = "C"
Case 4: ConvertToString = "D"
Case 5: ConvertToString = "D"
Case 6: ConvertToString = "F"
Case Default: ConvertToString = ""
End Select
End Function
``````
0

Commented:
Thats good one. I did not know that before. Thank you raterus
0

## Featured Post

• 2
Tackle projects and never again get stuck behind a technical roadblock.