Binding an enum to a WinForms combo box, and then setting it

前端 未结 28 2088
心在旅途
心在旅途 2020-11-28 04:33

a lot of people have answered the question of how to bind an enum to a combo box in WinForms. Its like this:

comboBox1.DataSource = Enum.GetValues(typeof(MyE         


        
28条回答
  •  攒了一身酷
    2020-11-28 04:48

    I use the following helper method, which you can bind to your list.

        ''' 
        ''' Returns enumeration as a sortable list.
        ''' 
        ''' GetType(some enumeration)
        Public Shared Function GetEnumAsList(ByVal t As Type) As SortedList(Of String, Integer)
    
            If Not t.IsEnum Then
                Throw New ArgumentException("Type is not an enumeration.")
            End If
    
            Dim items As New SortedList(Of String, Integer)
            Dim enumValues As Integer() = [Enum].GetValues(t)
            Dim enumNames As String() = [Enum].GetNames(t)
    
            For i As Integer = 0 To enumValues.GetUpperBound(0)
                items.Add(enumNames(i), enumValues(i))
            Next
    
            Return items
    
        End Function
    

提交回复
热议问题