selecting object in combobox

kerv21

New member
Joined
Nov 16, 2009
Messages
2
Programming Experience
Beginner
Hi I have a question about the combobox in vb.net.

The combobox I am using is not connected to a dataset or datasource. It is loaded manually via code using the following class:

VB.NET:
Public Class ListboxExtender
    Private sName As String
    Private iID As Integer

    Public Sub New()
        sName = ""
        iID = 0
    End Sub

    Public Sub New(ByVal Name As String, ByVal ID As Integer)
        sName = Name
        iID = ID
    End Sub

    Public Property Name() As String
        Get
            Return sName
        End Get

        Set(ByVal sValue As String)
            sName = sValue
        End Set
    End Property

    Public Property ItemData() As Integer
        Get
            Return iID
        End Get

        Set(ByVal iValue As Integer)
            iID = iValue
        End Set
    End Property

    Public Overrides Function ToString() As String
        Return sName
    End Function
End Class

So to load my listbox manually via code I do as follows:

combobox1.Items.Add(New ListboxExtender(rdr("Name"), rdr("DB_Key")))


Now if I want to select an existing item already loaded in the combobox I have tried:

combobox1.SelectedItem = New ListboxExtender(rdr("Name"), rdr("DB_Key"))

But this does not work like I thought it would.
Does anyone see what I am doing wrong ??

Thanks in advance for any assistance... I am stuck.
 
Well, I think I know why you can't select your previously added item using
 ComboBox1.SelectedItem = New ListboxExtender(rdr("Name"), rdr("DB_Key"))

You see, whenever you invoke "New ListboxExtender", you create a new instance of your ListboxExtender class. So, even if it has the same properties, it is not the same object, so you are trying to set your .SelectedItem property with an object that doesn't belong to the .Items collection.
This, however, would work in place of that statement:
        For Each item As ListboxExtender In ComboBox1.Items
            If item.Name = rdr("Name") And item.ItemData = rdr("DB_Key") Then
                ComboBox1.SelectedItem = item
            End If
        Next

But if rdr is a DataRow, it is perhaps simpler to do it without that custom class, this way:
        ComboBox1.DataSource = rdr.Table 'or the very datatable object whom rdr belongs to
        ComboBox1.DisplayMember = "Name"
        ComboBox1.ValueMember = "DB_Key"

I hope it helps. Good Luck!
 
Last edited:
Back
Top