I have an enumeration in the form:
Public Enum MyCollections As Integer
My_Stuff = 0
My_Things = 1
End Enum
I would like to use these as values in a ComboBox, but I would like to display the strings "My Stuff" and "My Things" respectively.
I'm sure I've seen a method for quickly creating some kind of local object definition where I can assign a string property to be displ开发者_如何学Pythonayed, and a "MyCollections" type property to store the value of the enum element, but I can't for the life of me think of how to explain that to a search engine.
Can anyone interpet my vague memories into some code I can use to set a DataSource for my ComboBox and retrieve the data when a user changes the selection?
I like creating a simple object and filling the ComboBox with a collection of my simple object. Then I set the DisplayMember property of the ComboBox to the name of the property I want displayed from my simple object.
'Something like this
Class SimpleObject
Property Name As String
End Class
'And then later...
comboBox.DisplayMember = "Name"
I think this is what you want - it enumerates the enumeration, listing the value and the text string of the value (taking out the underscores):
Dim enumValue As Integer, enumName As String
For Each enumValue In System.Enum.GetValues(GetType(MyCollections))
enumName = System.Enum.GetName(GetType(MyCollections), enumValue).Replace("_", " ")
Debug.WriteLine(enumValue.ToString + ";" + enumName)
Next
Output:
0;My Stuff
1;My Things
Putting this data into a combobox will require a databind which will probably require a custom class in your case but the code above may get you started.
Right, it looks as though I was thinking of "anonymous types". Here's some code that answer the (vary, very vague) question I as trying to ask:
Private Sub TestCodeForm_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
Dim addOutcomes As New Collection
For Each enumIn As MyCollections In [Enum].GetValues(GetType(MyCollections))
addOutcomes.Add(New With {.Display = [Enum].GetName(GetType(MyCollections), enumIn), .Value = enumIn})
Next
Me.ComboBox1.DisplayMember = "Display"
Me.ComboBox1.ValueMember = "Value"
Me.ComboBox1.DataSource = addOutcomes
End Sub
Private Sub ComboBox1_SelectedIndexChanged(sender As System.Object, e As System.EventArgs) Handles ComboBox1.SelectedIndexChanged
MsgBox("Display: " & CType(sender, ComboBox).SelectedItem.Display & vbCrLf &
"Value: " & CType(sender, ComboBox).SelectedItem.value.GetType.ToString)
End Sub
精彩评论