如何创建一个“内联”对象来包含ComboBox的成员?

时间:2011-10-04 15:07:27

标签: .net vb.net winforms combobox

我有以下形式的枚举:

Public Enum MyCollections As Integer
    My_Stuff = 0
    My_Things = 1
End Enum

我想在ComboBox中使用它们作为值,但我想分别显示字符串“My Stuff”和“My Things”。

我确定我已经看到了一种快速创建某种本地对象定义的方法,我可以在其中指定要显示的字符串属性,并使用“MyCollections”类型属性来存储枚举元素的值,但是我不能为我的生活想到如何向搜索引擎解释这一点。

任何人都可以将我模糊的记忆插入到一些代码中,我可以使用这些代码为我的ComboBox设置DataSource并在用户更改选择时检索数据吗?

3 个答案:

答案 0 :(得分:2)

我喜欢创建一个简单的对象,并用我的简单对象的集合填充ComboBox。然后我将ComboBox的DisplayMember属性设置为我想从简单对象显示的属性的名称。

'Something like this
Class SimpleObject
    Property Name As String
End Class

'And then later...
comboBox.DisplayMember = "Name"

答案 1 :(得分:1)

我认为这就是你想要的 - 它枚举了枚举,列出了值的值和文本字符串(取出了下划线):

    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

输出:

0;My Stuff
1;My Things

将这些数据放入组合框中需要一个数据绑定,在你的情况下probably require a custom class,但上面的代码可能会让你开始。

答案 2 :(得分:0)

是的,看起来好像我在考虑“匿名类型”。这里有一些代码可以回答我想要提出的(变化的,非常模糊的)问题:

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