AspAlliance.com LogoASPAlliance: Articles, reviews, and samples for .NET Developers
URL:
http://aspalliance.com/articleViewer.aspx?aId=1059&pId=-1
CodeSnip: How to Add Data/Values for Corresponding Entries in a Combo Box Using Visual Basic .NET
page
by Sandeep Acharya
Feedback
Average Rating: This article has not yet been rated.
Views (Total / Last 10 Days): 42330/ 53

Introduction

Most of the .NET developers used to experience a common problem while working with combo boxes. Generally, in a combo box or dropdown we used to store a value-text pair.  For example, suppose we have an employee Table in a Database where we have a unique Employee ID for each employee.  It is obvious that we will want to access the records by referring to the Employee ID's.

Now, assume a scenario where we need to display the list of employees in a Dropdown or combo box.  Displaying the list is not a big deal, but there is a twist in keeping the ID's against corresponding Employee Names in the Dropdown.  There is no direct method available in .NET to achieve this functionality.

Below is a code snippet that successfully implements the functionality in a twisted manner.  

System Requirements

·         Windows XP Professional SP2

·         Visual Studio .NET 2003 or Visual Studio 2005

Code Snippet

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 IntegerByVal 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

Few Questions

Q1. Why should one go for this implementation where viewmember, datamember and datasource can easily solve the issue?

Ans: Yes, viewmember, datamember and datasource could have solved this issue in an easier way if .Net would be bug free on this aspect.  We can use viewmember, datamember and datasource in the following manner.

Listing 4

With cmbEmployee
            .ValueMember = ""
            .DisplayMember = "asdasd"
            .DataSource = ""
End With

However, there is one flaw in this scenario.  While assigning the datasource to the combo box, the comboBoxName_ SelectedIndexChanged() gets fired.  That means the code written in this section will be executed again and again. (You can test this by putting a Message Box inside comboBoxName_ SelectedIndexChanged.)

Q2. Is this the only way for achieving the mentioned goal?

Ans: There might be other ways, but the idea behind all the logic is the same.  Basically, the logic behind all of it is that we are creating objects for each entry in the combo box and each object has a pair (Data and Description).

Downloads
Conclusion

This issue is not a new one and could have other solutions.  However, this code snippet uses a simple and meaningful way to achieve our goal.  I hope this will help all readers in their future coding life.


Product Spotlight
Product Spotlight 

©Copyright 1998-2024 ASPAlliance.com  |  Page Processed at 2024-04-25 7:12:14 AM  AspAlliance Recent Articles RSS Feed
About ASPAlliance | Newsgroups | Advertise | Authors | Email Lists | Feedback | Link To Us | Privacy | Search