Using an Enum as the DataSource for a ComboBox

12.19.06

While working on my spell check app Dyslexic Helper I had to use an Enum (System.Windows.Forms.keys) as a data source for a Combo box I found this to be very easy and very useful. Here is an example of how to do this.
Public Class frmExample
    'Enum to fill the combo box with
    Public Enum Names
        Jim
        Bob
        Dave
        Sam
        Tim
        Jon
        Suse
        Ann
        Sassy
        Silvia
    End Enum
    Private Sub FormExample_Load(ByVal sender As Object, _
  ByVal e As System.EventArgs) Handles Me.Load
        'fills the combo box with the names from the Enum Names
        Me.ComboBoxExample.DataSource = System.Enum.GetValues(GetType(Names))
        'selects the last selected name in the combobox
        'My.Settings.Name is defined in the project/properties/settings as a string
        Me.ComboBoxExample.SelectedIndex = Me.ComboBoxExample.FindStringExact(My.Settings.Name)
    End Sub
    Private Sub frmExample_FormClosing(ByVal sender As Object, _
  ByVal e As System.Windows.Forms.FormClosingEventArgs) Handles Me.FormClosing
        'saves the selected name in settings as form is closeing
        My.Settings.Name = Me.ComboBoxExample.Text
        My.Settings.Save()
    End Sub
End Class
You can download the source here.

CboExample.zip (50.48 KB)