Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / Languages / VB

Fill a ListBox with Text of an Enum

1.00/5 (1 vote)
12 Dec 2010CPOL 11.6K  

Introduction


Fills a ListBox with the Text Values of Every Item in a Enum

Background


This is an extention to the project located here
Convert Enums to DataTables

Using the code


Replace the REPLACE_THIS_WITH_YOUR_ENUM with your Enum, such as
Dim test As DataTable = EnumToDataTable(GetType(Aaron.Aaron_Components.Mod_Enum.Master_Tools.Tools_List), "", ""


Dim test As DataTable = EnumToDataTable(_
    GetType(REPLACE_THIS_WITH_YOUR_ENUM), "", 
			
'Original is Located at
'http://www.codeproject.com/KB/vb/EnumToDataTable.aspx?msg=3676779#xx3676779xx
'-----------------------------------------------------------------------
Imports System.Data
Public Class Form5

    Public Function EnumToDataTable(ByVal EnumObject As Type, _
       ByVal KeyField As String, ByVal ValueField As String) As DataTable
        Dim oData As DataTable = New DataTable
        Dim oRow As DataRow = Nothing
        Dim oColumn As DataColumn = Nothing
        If KeyField.Trim() = String.Empty Then KeyField = "KEY"
        If ValueField.Trim() = String.Empty Then ValueField = "VALUE"
        oColumn = New DataColumn(KeyField, GetType(System.Int32))
        oData.Columns.Add(KeyField)
        oColumn = New DataColumn(ValueField, GetType(System.String))
        oData.Columns.Add(ValueField)
        '-------------------------------------------------------------
        For Each iEnumItem As Object In [Enum].GetValues(EnumObject)
            oRow = oData.NewRow()
            oRow(KeyField) = CType(iEnumItem, Int32)
            oRow(ValueField) = StrConv(Replace(iEnumItem.ToString(), "_", " "), _
                  VbStrConv.ProperCase)
            oData.Rows.Add(oRow)
        Next
        '-------------------------------------------------------------
        Return oData
    End Function
    ''' <summary>
    ''' Handles the Click event of the Button1 control.
    ''' aLSO THIS IS WHERE YOU SET UP THE ENUM
    ''' </summary>
    ''' <param name="sender">The source of the event.</param>
    ''' <param name="e">The <see cref="System.EventArgs" /> instance containing the event data.</param>
    Private Sub Button1_Click(ByVal sender As System.Object,_
        ByVal e As System.EventArgs) Handles Button1.Click

        '----------------------------------------
        Dim test As DataTable = EnumToDataTable(GetType(REPLACE_THIS_WITH_YOUR_ENUM), "", "") '<----
        '----------------------------------------
        ListBox1.Items.Clear()
        For Each Item As System.Data.DataRow In test.Rows
            ListBox1.Items.Add(Item.Item(1))
        Next
    End Sub
End Class

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)