Recipe 3.13. Converting Between Numeric and String Enumeration Values


Problem

While you intend to use an enumeration through its members and their numeric equivalents, you also need to be able to get the string name of an enumeration member and convert it back to numeric form from that string.

Solution

Use the string conversion features of the System.Enum class and its derived enumerations to manipulate the members through strings.

Discussion

Moving from a numeric member to string form is simple, and you've probably already done something similar for other types. Let's reuse the enumeration from Recipe 3.12:

 Enum StorageMedia    Floppy    CD    DVD    FlashRAM    Paper End Enum 

If you've created an enumeration variable:

 Dim storageType As StorageMedia = StorageMedia.FlashRAM 

you can convert its value to string form using the ToString() member:

 Dim stringForm As String = storageType.  ToString() MsgBox(stringForm) ' Displays "FlashRAM" 

Converting back from a string is just slightly more indirect. Use the System.Enum class's Parse() method to restore a string back to its original numeric value:

 storageType = System.Enum.  Parse(GetType(StorageMedia), "DVD") MsgBox(CInt(storageType))     ' Displays 2 MsgBox(storageType.ToString)  ' Displays "DVD" 

Visual Basic compiles the full name of each enumeration member into the target application. You can take advantage of these stored names to shuttle enumeration values between their integer and string forms.

If you pass an invalid string to the Parse() method, an error will occur, so keep an eye on that enumerated data.




Visual Basic 2005 Cookbook(c) Solutions for VB 2005 Programmers
Visual Basic 2005 Cookbook: Solutions for VB 2005 Programmers (Cookbooks (OReilly))
ISBN: 0596101775
EAN: 2147483647
Year: 2006
Pages: 400

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net