Combobox valuemember - how to set?

Mondeo

Centurion
Joined
Nov 10, 2006
Messages
128
Location
Sunny Lancashire
Hi,

I have a combobox on a form, I noticed that unlike the dropdownlist in asp.net which has a collection of ListItems the combobox can hold any object. So I created a ListItem class to use.
Visual Basic:
Public Class ListItem
    Dim _text, _value As String

    Property Text() As String
        Get
            Text = _text
        End Get
        Set(ByVal val As String)
            _text = val
        End Set
    End Property

    Property Value() As String
        Get
            Value = _value
        End Get
        Set(ByVal val As String)
            _value = val
        End Set
    End Property

    Sub New(ByVal inText As String, ByVal inValue As String)
        Me.Text = inText
        Me.Value = inValue
    End Sub

    Public Overrides Function ToString() As String
        Return Me.Text
    End Function
End Class

Then I added items to the combobox like this

Dim li as new listitem("My Text","My Value")
cboDealers.Items.Add(li)

I want to bind the value of the combobox to a datasource using Databindings.Add, but which property contains the value, is it a property of the listitem class I need to use or the combobox itself?

Thanks
 
just a quick fyi, when you have a combobox that you have added objects to, you have two options for setting that combobox to the specific object you want.
1. use .SelectedItem = myobject, and myobject must be an object in the list of items you added to the combobox
2. use .Text = mytext, where that matches the ToString of one of your objects.

so likewise, when the user changes a combobox, you can get the object via .SelectedItem, or you can get the ToString property of it by saying cbo.Text.


now for the binding, since you're overriding ToString with Me.Text, and you're wanting the Value instead, you're going to need the cbo.SelectedItem.Value property.

Whether or not you're able to bind that, I'm not sure. I don't use binding b/c i received a few lectures that it was bulky and slows down large apps, so I never pursued it any further. (Instead, on the SelectedIndex_Chaned event for the combobox, i capture the .SelectedItem and then update my table. If your combobox name matches your column's name, you can do this with one handler)
 
Back
Top