Storing Items as Objects To Combo Box (VB.NET)

This applies to Microsoft .NET Framework programming.

The purpose of storing objects instead of string to combo box is to allow for other information to be stored as well.

For instance, instead of just storing the text, we may also want to store the index key.

To give you a very good example.

Let's say you want to store a record where the name=Ali in combobox.

But at the same time, you also want to store the index key alongside this information so the same record can be referenced back from the database (datasource).

If you are using textbox, it is possible to do this using the tag property, however in combo box, you can't do that.

Thus, you got to do it by storing the item as object instead of string.

The tricky part is that when you do that, by default, the combo box will display the instance name of the object instead of its intended property such as the name.

Refer to 'vs-issues-sep-2011-10.jpg'


The solution is to create an 'Overrides' function for ToString.

Refer to 'vs-issues-sep-2011-11.jpg'


1.) Create a customized class.

Public Class clsA

    Private recID As Integer
    Private myName As String

    Public Property VAR_recID() As Integer
        Get
            VAR_recID = recID
        End Get
        Set(ByVal value As Integer)
            recID = value
        End Set
    End Property

    Public Property VAR_myName() As String
        Get
            VAR_myName = myName
        End Get
        Set(ByVal value As String)
            myName = value
        End Set
    End Property

End Class

2.) Create instances of clsA and add those instances to the combo box.

'--- create new object relational
            objCol = Nothing
            objCol = New Collection

            For i = 1 To 10
                objA = New clsA

                objA.VAR_recID = i
                objA.VAR_myName = "brandon " & i

                If Not objCol Is Nothing Then
                    Call objCol.Add(objA, i)
                End If

                objA = Nothing

            Next i

            '--- Add to combo box ---
            If Not objCol Is Nothing Then

                For i = 1 To objCol.Count
                    objA = objCol.Item(i)
                    Call ComboBox1.Items.Add(objA)
                    objA = Nothing

                Next i
            End If


3.) Create an 'Overrides' function for ToString inside class clsA.

Public Overrides Function ToString() As String

        Try
            ToString = myName
        Catch ex As Exception
            ToString = DirectCast(Me, Object).ToString
            MsgBox(ex.ToString & vbCrLf & ex.Message & vbCrLf & ex.StackTrace)
        End Try

    End Function


Download the sample codes (VB.NET Visual Studio 2008 SP1) for detail.

Comments