Binding a ComboBox in VB.NET

This code snippet shows how to bind a control to an enumeration in VB.NET.
  • 5539

The GetValues method of Enum returns an array of objects. We can use this method to convert an enum to an array and bind to a ComboBox in Windows Formsusing DataSource property.

The following code snippet binds ButtonState enum available in Windows Forms to a ComboBox.

ComboBox1.DataSource = System.Enum.GetValues(GetType(System.Windows.Forms.ButtonState))

Now, once we have an enum bound to a ComboBox, we need to the selected item from ComboBox and convert back to the enum. Unfortunately, ComboBox selected item gives us a string. Now we will have to convert back to the string value to an enum value.

For that, we can use Enum.Parse method and cast it to the enumeration.

The following code snippet takes the selected value in a ComboBox and converts it back to an enum value.

Dim currentState As ButtonState = _

System.Enum.Parse(GetType(ButtonState), ComboBox1.Items(ComboBox1.SelectedIndex).ToString())




More Articles

© 2020 DotNetHeaven. All rights reserved.