genespos genespos - 5 months ago 70
Vb.net Question

Set DisplayMember and ValueMember on ComboBox without DataSource

I would like to have a

DisplayMember
and a
ValueMember
on a
ComboBox
which has only 4 values and they are always the same.

Is it possible without using a
DataTable
as
DataSource
and without creating a class?

I would like to have something like:

ValueMember
= "Fixed"

DisplayMember
= "Specific and unique number"

ValueMember
= "Multiple"

DisplayMember
= "Multiple and different numbers"

ValueMember
= "Repeated"

DisplayMember
= "One number repeated x times"

Answer

You could use the existing NET KeyValuePair class to link a value with a name:

cbox.Items.Add(New KeyValuePair(Of String, String)("Specific", 
         "Specific and unique number"))
cbox.Items.Add(New KeyValuePair(Of String, String)("Multiple", 
         "Multiple and different numbers"))
cbox.Items.Add(New KeyValuePair(Of String, String)("Repeated", 
         "One number repeated x times"))

cbox.ValueMember = "Key"
cbox.DisplayMember = "Value"

You could also use an anonymous type:

cbox.Items.Add(New With {.Name = "Fixed...", .Value = "Specific"})
cbox.Items.Add(New With {.Name = "Multiple...", .Value = "Multiple"})
cbox.Items.Add(New With {.Name = "Repeated...", .Value = "Repeated"})
...

You might want to consider using an enum for the choices, and associate the text as the Description:

Public Enum Things
    <Description("Specific and unique number")> Fixed
    <Description("Multiple and different numbers")> Multiple
    <Description("One number repeated x times")> Repeated
End Enum

It takes a bit to get the Description, but can be used to build an anonymous type:

Dim values = [Enum].GetValues(GetType(Things))
Dim descr As String

For Each n As Things In values
    descr = GetDescription(n)
    cbox.Items.Add(New With {.Name = descr, .Value = n})
Next
cbox.ValueMember = "Value"
cbox.DisplayMember = "Name"

You could combine this with the first and use a KeyValuePair(Of Things, String) for the cbo items. Helper:

Public Shared Function GetDescription(EnumConstant As [Enum]) As String

    Dim t As Type = EnumConstant.GetType()
    Dim attr = CType(t.GetField([Enum].GetName(t, EnumConstant)).
                    GetCustomAttribute(GetType(DescriptionAttribute)), 
                    DescriptionAttribute)

    If attr IsNot Nothing Then
        Return attr.Description
    Else
        Return EnumConstant.ToString()
    End If
End Function

Which one is "best" depends partly on preference and how it is used. I would lean towards the Enum.