Solved

Populating ComboBoxes in VS 2008 Using VB.NET

Posted on 2010-09-22
11
709 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
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
3 Use Cases for Connected Systems

Our Dev teams are like yours. They’re continually cranking out code for new features/bugs fixes, testing, deploying, testing some more, responding to production monitoring events and more. It’s complex. So, we thought you’d like to see what’s working for us.

 
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

Courses: Start Training Online With Pros, Today

Brush up on the basics or master the advanced techniques required to earn essential industry certifications, with Courses. Enroll in a course and start learning today. Training topics range from Android App Dev to the Xen Virtualization Platform.

Question has a verified solution.

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

Wouldn’t it be nice if you could test whether an element is contained in an array by using a Contains method just like the one available on List objects? Wouldn’t it be good if you could write code like this? (CODE) In .NET 3.5, this is possible…
A long time ago (May 2011), I have written an article showing you how to create a DLL using Visual Studio 2005 to be hosted in SQL Server 2005. That was valid at that time and it is still valid if you are still using these versions. You can still re…
This is used to tweak the memory usage for your computer, it is used for servers more so than workstations but just be careful editing registry settings as it may cause irreversible results. I hold no responsibility for anything you do to the regist…
Two types of users will appreciate AOMEI Backupper Pro: 1 - Those with PCIe drives (and haven't found cloning software that works on them). 2 - Those who want a fast clone of their boot drive (no re-boots needed) and it can clone your drive wh…

815 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

Need Help in Real-Time?

Connect with top rated Experts

8 Experts available now in Live!

Get 1:1 Help Now