Solved

Populating ComboBoxes in VS 2008 Using VB.NET

Posted on 2010-09-22
11
726 Views
Last Modified: 2012-08-13
Hello,

I am building a VS 2008 VB.NET Windows Application.  I have a combobox that I would like to populate with different strings for the text and value property of each item in the combobox.  I believe the syntax mycombobox.Items.Add("xxx") would assign "xxx" to both the text and value properties.  But what if I wanted the text property to be "xxx", and the value property to "yyy".  Can anyone tell me the command syntax to use?

Thank you, Stu Engelman
0
Comment
Question by:stuengelman
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
11 Comments
 
LVL 11

Expert Comment

by:anyoneis
ID: 33740499
Generally speaking, you want the item collection to be a collection of objects with multiple properties. You then set DisplayMember to the name of the property you want to display, and ValueMember to the name of the property you want as the value.
David
0
 

Author Comment

by:stuengelman
ID: 33740549
Hi David,

If I'm understanding you correctly, my code would probably be something like this:

Dim zzz as New ControlName
zzz.DisplayMember="xxx"
zzz.ValueMember="yyy"
mycombobox.Items.Add(zzz)

My question is: what should I use for ControlName?
0
 

Author Comment

by:stuengelman
ID: 33740704
Hi David,

I did some hunting around, and it looks like the object I need is ComboBoxItem.  I.e., the code would be mycombobox.Items.Add(new ComboBoxItem("display","value")).  But ComboBoxItem throws a design time error of "Type Not Defined".  According to the Object Browser, ComboBoxItem is a member of System.Windows.Controls, but I can't create a reference to this class in my Project References tab, and using the statement "Imports System.Windows.Controls" throws a design time error saying the class can't be found or has no public members.

Stu
0
Turn Insights Into Action

You’ve already invested in ITSM tools, chat applications, automation utilities, and more. Fortify these solutions with intelligent communications so you can drive business processes forward.

With xMatters, you'll never miss a beat.

 
LVL 55

Accepted Solution

by:
Jaime Olivares earned 250 total points
ID: 33740708
what you should add is an object, not a string. Let's say you have a MyData class with properties Name and Value.
Then you have a collection containing multiple objects of class MyData

Dim coll as new ArrayList
Dim zzz as new MyData
zzz.Name = "Mary"
zzz.Value = 100
coll.Add(zzz)

mycombobox.DisplayMember = "Name"
mycombobox.ValueMember = "Value"
mycombobox.DataSource = coll

0
 

Author Comment

by:stuengelman
ID: 33740765
OK, I get it.  You're saying I have to bind the combobox to an arraylist.

I found out just now that the ComboBoxItem only exists for with WPF/XAML, explaining why I couldn't declare it on a standard Windows form.

Let me try your method and report back.

Stu
0
 
LVL 29

Expert Comment

by:nffvrxqgrcfqvvc
ID: 33740840
You may also create your own class and override ToString() here is an example that might help you.

Public Class Form1

    Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        ComboBox1.Items.Add(New Stuff("Display1", "123"))
        ComboBox1.Items.Add(New Stuff("Display2", "456"))
        ComboBox1.Items.Add(New Stuff("Display3", "789"))
    End Sub

    Private Sub ComboBox1_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ComboBox1.SelectedIndexChanged
        Dim item As Stuff = DirectCast(ComboBox1.SelectedItem, Stuff)
        Debug.Print("{0}    {1}", item.DisplayMember, item.ValueMember)
    End Sub

End Class

Public Class Stuff
    Private _displayMember As String
    Private _valueMember As String
    Protected Friend Sub New(ByVal displayMember As String, _
                             ByVal valueMember As String)
        Me._displayMember = displayMember
        Me._valueMember = valueMember
    End Sub
    Public ReadOnly Property DisplayMember As String
        Get
            Return _displayMember
        End Get
    End Property
    Public ReadOnly Property ValueMember As String
        Get
            Return _valueMember
        End Get
    End Property
    Public Overrides Function ToString() As String
        Return _displayMember 'displayed in the combobox
    End Function
End Class

Open in new window

0
 

Author Comment

by:stuengelman
ID: 33749067
Hi egl1044,

I attempted your method.  I created a class module with the following code:

Public Class CtlListLoader
    Private _displayMember As String
    Private _valueMember As String
    Protected Friend Sub New(ByVal displayMember As String, ByVal valueMember As String)
        Me._displayMember = displayMember
        Me._valueMember = valueMember
    End Sub
End Class

In my form, I used the syntax for loading the combobox cbMIMember as follows:

cbMIMember.Items.Add(New CtlListLoader(cbtxt, CStr(RDR("MemberID")))),

where cbtxt is a string variable is loaded with a person's name, and RDR("MemberID") is that person's member ID from the database.

I tried displaying the value of cbMIMember.SelectedText and cbMIMember.SelectedValue in a msgbox, but both were blank, even though the code explicitly selects the first combobox listitem.

Also, the text in the combobox's listitems was "MMCApplication.CtlListLoader" for each listitem, instead of the person's name (MMCApplication is the name of the application).

Could you please advise?

Thanks, Stu
0
 
LVL 29

Expert Comment

by:nffvrxqgrcfqvvc
ID: 33749221
You need to override ToString() method and return what you would like to see in the display of the combobox like in the example Stuff class. =)
0
 

Author Comment

by:stuengelman
ID: 33749338
Hi egl1044,

I'm confused about two points:

(1) I'm not using the ToString() method in the code snippets we are discussing, so I'm confused as to why I need to overrride what is in the BCL for the ToString() method.

(2) If I use the ToString() method within a form for a purpose unrelated to the issue we are discussing, I would want the method to work in the usual way (convert a numeric or date to a string), not return the last "_displayMember" setting from the custom class.

Stu
0
 
LVL 29

Expert Comment

by:nffvrxqgrcfqvvc
ID: 33749599
In the example your creating your own class object that you can *Add into the ComboBox when you add the item the ComboBox will call ToString() in this case if your passing an Object(Stuff Class) and you don't override ToString() its going to display ApplicationName.Stuff... If you override ToString() and return what you would like to see displayed in the ComboBox it will use that value instead. You can extend the class with additional properties ... Then when a selection is made the ComboBox will pass the *Object (Stuff Class) which you can cast to a Stuff object because you know thats what the type of Object is expected then you can obtain the information you populated when you added it to the ComboBox.
0
 

Author Closing Comment

by:stuengelman
ID: 33785442
Great job, worked perfectly.  Thank you
0

Featured Post

Online Training Solution

Drastically shorten your training time with WalkMe's advanced online training solution that Guides your trainees to action. Forget about retraining and skyrocket knowledge retention rates.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

This article describes relatively difficult and non-obvious issues that are likely to arise when creating COM class in Visual Studio and deploying it by professional MSI-authoring tools. It is assumed that the reader is already familiar with the cla…
Parsing a CSV file is a task that we are confronted with regularly, and although there are a vast number of means to do this, as a newbie, the field can be confusing and the tools can seem complex. A simple solution to parsing a customized CSV fi…
This is a high-level webinar that covers the history of enterprise open source database use. It addresses both the advantages companies see in using open source database technologies, as well as the fears and reservations they might have. In this…
Monitoring a network: how to monitor network services and why? Michael Kulchisky, MCSE, MCSA, MCP, VTSP, VSP, CCSP outlines the philosophy behind service monitoring and why a handshake validation is critical in network monitoring. Software utilized …

691 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question