Bind a Combo Box to an Enumeration in Visual Studio .NET
Provided by: Jim Ferguson, Project Manager
An enumeration is a related set of constants. The enumeration members
between the Enum and End Enum statements are initialized to constant values.
Enumeration is used to group a set of constants under a common name, so the
value can be referred to by a string value rather than the numeric value.
For example, this enumeration provides a list of constants for the provided
names:
Private Enum
PeopleNames
bob
mary
jane
joe
fred
End Enum
By default, the first enumerator has a value of 0, and each successive
enumerator is one larger than the value of the previous one, unless you
explicitly specify a value for a particular enumerator. The value for "bob"
is 0, "mary" is 1, and so on to "fred" which is 4.
It is possible to bind a combo box or a list box to the values in the
enumeration so that the values in the dropdown list are the string names,
but the underlying constant values can be retrieved from the selected item.
The Enum class provides a static method called "GetValues" which returns an
array of all items in the enumeration. You can bind a combo box to this
enumeration with code such as the following:
Me.ComboBox1.DataSource = _
System.Enum.GetValues(GetType(PeopleNames))
The argument to GetValues is a type value for the enumeration you wish to
retrieve. GetType returns a type object based on the name of the
enumeration. Change this value to the name of the enum you are interested
in.
After this line of code executes the list portion of the combo box contains
the names "bob", "mary", "jane" etc. If you just want to know which name was
selected you can use the .SelectedText property of the combobox. However if
you want to know the constant value associated with the name, you need to
use the .SelectedValue property (which is a generic object) and cast it to
the type of enum you are interested in. In this example:
Dim nameid As
PeopleNames =
CType(ComboBox1.SelectedValue, PeopleNames)
The variable "nameid" contains a 0, or 1, or 2 etc. depending on the value
of the enumerated item that is currently selected.
Return to the tips page
|