In order to achieve this functionality we need to construct
a class of our own. We can use the objects of this class wherever we need this
functionality to be implemented. The code for generating the class is given
below.
Listing 1
Public Class DataDescription
Public Data As Integer
Public Description As String
Public Sub New(ByVal Newdata As Integer, ByVal NewDescription As String)
Data = Newdata
Description = NewDescription
End Sub
Public Overrides Function ToString() As String
Return Description
End Function
End Class
Every Object of the above class will hold two values in it.
Data: The background ID or Value or
Data for corresponding displayed texts.
Description: The text or String that
needs to be displayed.
Now, we can use this class by creating its objects. The
following example shows the use of the above Class.
Listing 2
Private Sub Form1_Load(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles MyBase.Load
Dim sQuery As New System.Text.StringBuilder()
Dim oDataTable As New DataTable()
Dim oDataRow As DataRow
sQuery.Append("SELECT employeeId, employeeName From employees ")
oDataTable = New doDBConnection().doDBconnection(sQuery.ToString, _
"Employee")
For Each oDataRow In oDataTable.Rows
cmbEmployee.Items.Add(New DataDescription( _
oDataRow.Item("employeeId"), _
oDataRow.Item("employeeName")))
Next
End Sub
The above code snippet shows the use of the class DataDescription.
The FOR loop towards the end is adding the ITEMS to the combo box/dropdown is
a loop. Inside this loop we are using DataDescription class to create the Id/data
and description pairs. These pairs are added to the dropdowns.
Hve a look at the accessing method of the data and
descriptions from the combo box.
Listing 3
Private Sub cmbEmployee_SelectedIndexChanged( _
ByVal sender As System.Object, _
ByVal e As System.EventArgs) _
Handles cmbEmployee.SelectedIndexChanged
MsgBox("Selected Item : " & _
cmbEmployee.SelectedItem.Description.ToString & _
vbCrLf & _
"Corresponding Value : " & _
cmbEmployee.SelectedItem.data.ToString, _
MsgBoxStyle.OKOnly, "Combo Box Issue is solved")
End Sub
The above code is written to get the details of the
SelectedItem from the Combo Box. One can easily notice the use of the member
variables (Data, Description) of the newly created Class DataDescription for
accessing the Selected Items.
The mentioned code will generate a message box displaying
the Display Text with the underlying Data for the SelectedItem. It will look
like the following.
Figure 1