CodeSnip: How to Add Data/Values for Corresponding Entries in a Combo Box Using Visual Basic .NET
 
Published: 06 Nov 2006
Abstract
While using Visual Basic .NET many developers have experienced a drawback in maintaining data or value for corresponding entries in a combo box. In this article Sandeep provides a solution for the issue with the help of code samples.
by Sandeep Acharya
Feedback
Average Rating: This article has not yet been rated.
Views (Total / Last 10 Days): 42424/ 27

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.



User Comments

Title: Combo Box value pair   
Name: Albert
Date: 2010-08-10 4:17:21 PM
Comment:
OK,
But now you like to take the values out of a CVS file. What are the changes to listing 2
Title: mr   
Name: praveen
Date: 2009-12-17 8:04:51 AM
Comment:
i dnt know how to add item in the combobox,even i dont no coding
Title: Combo Box   
Name: Khadar
Date: 2009-03-31 4:04:07 PM
Comment:
Hello I am a new C# user and i wanted to know how to add item in the combo Box. Please anybody help
Title: Mr   
Name: WillC
Date: 2009-02-03 10:59:44 AM
Comment:
This is the simplest solution to this I can find. And it works. Thank you.
Title: Excellent Sandeep   
Name: Rahul Gupta
Date: 2008-01-09 7:16:47 AM
Comment:
Done good work,
it really solved the problem,
but mention it because of override of toString function

Thanking you
Rahul Gupta
Software Developer
www.maestros.net
Title: anal programmer   
Name: paris hilton
Date: 2007-06-02 8:12:40 AM
Comment:
TOPS!!great article.Thank you.
Title: Web Application Developer   
Name: Liby George
Date: 2007-05-13 1:13:09 PM
Comment:
Very Nice and it is working fine. Thanks...

Liby George
Title: Want some Exercise???   
Name: Neetu
Date: 2007-04-23 5:01:39 AM
Comment:
It's Really nice and very helpful stuff .
But I request you to give me the only exercise for C#.net
I want to practice by applying the logics on the projects.
Please can you help me out of this???
If you have wny questions kindly revert me back on my email id as adwani_neetu@yahoo.co.in
Also Can I get totally C# Concepts/tutorial on internet.
If yes then send me the link to my email id.

Thanks & Regards,
Neetu
Title: Select a combo item by Value   
Name: Jus
Date: 2007-04-23 1:30:51 AM
Comment:
Ahh... Sandeep, just spotted previous entry. Thought I would have to do that.
Title: Select a combo item by Value   
Name: Jus
Date: 2007-04-23 1:25:35 AM
Comment:
Ok - so how would you set the currently selected item in the list by it's Value.
Normally I would use cbo.SelectedValue = xxx to set the current item.
Title: Cool   
Name: wackoyacky@yahoo.com.ph
Date: 2007-02-03 7:50:57 PM
Comment:
Cool work around! Very helpful especially for webby guys who's used with asp.net dropdownlist like me! :)
Title: Very Good   
Name: Raef
Date: 2007-01-26 4:17:26 AM
Comment:
Thank you very much .. this is really a hot topic i keep searching for this code long time ago
Title: An issue.. Please help!   
Name: Kathir
Date: 2007-01-17 2:59:07 AM
Comment:
Hi Sandeep,
It's a great tip!
Sandeep - I have an issue. I'm using VS.NET 2003 Enterprise Architect and i'm not getting the property DATA of ComboBox1.SelectedItem. Is this the problem withe version and edition i'm using?
Thanks.
Title: For Karunya   
Name: Sandeep
Date: 2007-01-05 11:43:10 AM
Comment:
Hello Karunya,
Try something like this :
*********************************************************

For Each oDataRow In oDataTable.Rows
cmbEmployee.Items.Add(New DataDescription( _
oDataRow.Item("employeeId"), _
oDataRow.Item("employeeName")))
If CInt(oDataRow.Item("employeeId")) = 6 Then
cmbEmployee.SelectedIndex = cmbEmployee.Items.Count - 1
End If
Next
********************************************************
The above lines of code sets the SelectedIndex at the time of populating the dropdown.

You can also take another loop to cover the entire dropdown items and then inside that check for the appropriate dropdown.data.

I guess you may solve your problem by using any of them. But I suggest the first one as the second one involves an extra loop.

please feel free to ask any doubts if you have.

Thanks

Sandeep
Title: Setting the Selected Index using the data value   
Name: Karunya
Date: 2007-01-05 11:22:08 AM
Comment:
This solution has fixed the text/value issues. Thanx.

I have a question.
I am trying to set the selected index of the combo box, with the data(value).

Something like 'cbxEmployee.SelectedItem.Data = empCode'

I would appreciate any kindof help.

Thanx
Title: No the event will not get fired for each entry in the collection.....   
Name: Vikram.
Date: 2006-12-09 11:53:33 PM
Comment:
Please do verify this yourself.. I have verified this... the selectedindexchanged event is fired only once for the item displayed in the combox box!!!!!
Title: nice   
Name: K.senthilkumar
Date: 2006-11-24 6:13:48 AM
Comment:
thank u,,i know about how to full both text and value in ASP.net but i dont know in VB.net but with the help of u, i have cleared my doubts....
Title: good for beginner   
Name: Sandeep
Date: 2006-11-13 5:44:17 AM
Comment:
this is very useful to the beginners and also to me
Title: Some other options, things to consider   
Name: Christopher May
Date: 2006-11-10 12:44:18 PM
Comment:
I wrote up some comments and other options on my blog:

http://www.chrismay.org/2006/11/10/Dealing+With+WinForms+Combobox+And+Namevalue+Items.aspx
Title: Thanks, Nice post on the Confusion   
Name: Sumit Kumar Dhal
Date: 2006-11-07 2:14:03 AM
Comment:
Nice job Sandeep,
This, will help most to achive the solution.
More, this article made me understand, how I can utilize my own classes/objects in a more meaningful way, to optimize the .net control usage.

But, i have a question, not to you, but all microsoft people, why they do not have name-value property combination, in to the combo item type.
Can I conclude that there is a lot more scope to make .net more developer friendly :)

sumit
Title: Nice and informative.   
Name: Sarit
Date: 2006-11-06 1:34:16 AM
Comment:
This sol will solve many problem dealing with text/value issues.

Product Spotlight
Product Spotlight 





Community Advice: ASP | SQL | XML | Regular Expressions | Windows


©Copyright 1998-2024 ASPAlliance.com  |  Page Processed at 2024-04-18 5:57:22 PM  AspAlliance Recent Articles RSS Feed
About ASPAlliance | Newsgroups | Advertise | Authors | Email Lists | Feedback | Link To Us | Privacy | Search