Written by WATYF on Wednesday, 28 September 2005 (7123 hits)
Category: .NET Programming
Here's a little tip I picked up... I figured I'd pass it along.
Let's say you've got an enumerator... lets also say that you want to give your user the option to pick one of the items in that enumerator by using a ComboBox (or ListBox or whatever). Well... once they pick which item they want, the combobox returns a plain ol' string, not an item from the enumerator. Well what good does that do you? Now you've got this string, and you need to convert it to the corresponding value of that item in the enumerator... So what do you do? How do you take a String and quickly and easily return it's corresponding value from an Enumerator.... Well, how 'bout I show you.
Let's say we're making our own file properties editor and we want the user to be able to pick the file's property from a combobox (yes... I realize that this isn't practical... but I needed something simple for the example ) Well... we could just type all the possible file attributes into the combobox and then when the user selects one, would could just use a bunch of If statements (or Select Case) to determine which one they picked and return the appropriate value... like so:
Function GetAttr(sItm as String) as Integer
If sItm = "Hidden" Then
Elseif sItm = "ReadOnly" Then
But really... who wants to do all that typing? I sure don't... You gotta sit there and type in every possible attribute into the combobox item collection... then you gotta write all those select/if statements to catch each one and return the right value... psshhh! No thank you... I'm much too lazy for that.
So instead.. first, we will get the items from the enumerator into the combobox by looping through the enum and loading each item to the combobox during the Form_Load event (or whatever event suits you). Check it:
For Each itm As Object In [Enum].GetValues(GetType(FileAttributes))
Now... our combobox has all the attributes in it, and the user can select them at their leisure. Then, when you need to process their selection... you have two choices (depending on your needs).
1) If you want to do processing of multiple values, or want to do side processing on each enum value (or whatever), then you can loop through the same enum, and check the text of the combobox against the enum item, and if they match, you can return the item's value. Peep this:
Function GetAttr(ByVal sItm As String) As Integer
For Each itm As Object In System.Enum.GetValues(GetType(FileAttributes))
If itm.ToString = sItm Then Return CType(itm, Integer)
Or 2) The more direct approach would be to directly convert the String to its corresponding enum value using the Parse method of the Enum class. Blam!:
So there you go... you can present the user with the name of each item in an enum.... they can pick one... and you can return the value of which item they picked... all in about 4-8 lines of code... is that sweet or what?