Adding enum to a combo
January 27th, 2009
In the propertyBrowser when an Enum is exposed you select from the enums descriptions (Like you do in the IDE). I needed to do this at runtime in a form. The user needs to select a value from an enum so I wanted to populate a combobox for easy selection. In this example we allow the user to select a variable type:-
ComboToPopulate.Items.AddRange([Enum].GetNames(GetType(TypeCode)))
TypeCode is the enum that represent basic variables in .Net (String, Integer etc). To get the value back just use the following:-
Dim OurType as TypeCode OurType = [Enum].Parse(GetType(TypeCode), ComboToPopulate.Text) TargetEnum variable = (TargetEnum)Enum.Parse(typeof(TargetEnum), "Enums string");
I hope this helps. I spent ages doing this in many ways and finally refined it down to this. When using Option Strict in ASP.Net the above technique does not work so here is a function to do it. Try the other way first though.
Public Sub EnumToCombo(ByRef EnumToUse As System.Type, ByRef DDL As DropDownList) Dim Names() As String Dim Values As System.Array Dim index As Int32 Names = [Enum].GetNames(EnumToUse) Values = [Enum].GetValues(EnumToUse) DDL.Items.Clear() For Index = 0 To Names.Length - 1 DDL.Items.Add(New ListItem(Names(index), CStr(Values.GetValue(index)))) Next End Sub
public static void EnumToListItemCollection(System.Type EnumToUse, ListItemCollection ListItems) { string[] Names; System.Array Values; Int32 index; Names = Enum.GetNames(EnumToUse); Values = Enum.GetValues(EnumToUse); ListItems.Clear(); for (index = 0; index < = Names.Length - 1; index++) { ListItems.Add(new ListItem(Names[index], Values.GetValue(index).ToString())); } }