Solved

Combobox in windows Form

Posted on 2011-09-07
13
754 Views
Last Modified: 2012-05-12
I want to use a combobox where one column would be an ID and the other column the data,
Here is FillCombo code that I'm trying to make work.  Problem is "selectedValue" always returns nothing.
    Sub FillCombo()
        Dim i As Integer, M As String
        For i = 0 To 19
            cboBookmarks.SelectedValue = "Id" & Str(i)
            M = "Data" & Str(i)
            cboBookmarks.SelectedText = M
            cboBookmarks.Items.Add(M)
        Next (i)
        cboBookmarks.Text = "item"
    End Sub

    Private Sub cboBookmarks_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cboBookmarks.SelectedIndexChanged
        Dim index As Integer = cboBookmarks.SelectedIndex
        Dim Item As String = cboBookmarks.SelectedItem
        Dim Value As String = cboBookmarks.SelectedValue
        '
        MsgBox("Selected = '" & Item & "', and the ID Value ='" & Value & "'")
        RunMMtest.Focus()
    End Sub

Open in new window

Can someone explain what I'm doing wrong, and provide a sample that works?

Thanks
0
Comment
Question by:FrankBabz
  • 5
  • 3
  • 2
  • +1
13 Comments
 
LVL 38

Expert Comment

by:Tom Beck
ID: 36502250
Line 4 is not doing anything because it does not refer to any particular item in the combobox. You need something a little more complex. Try the code below.
Sub FillCombo()
        Dim i As Integer
        For i = 0 To 19
            cboBookmarks.Items.Add(New ComboBoxItem("Data" & Str(i), "Id" & Str(i)))
        Next (i)
        cboBookmarks.Text = "item"
    End Sub

    Private Sub cboBookmarks_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cboBookmarks.SelectedIndexChanged
        Dim selectedItem As ComboBoxItem = CType(cboBookmarks.SelectedItem, ComboBoxItem)
        Dim Item As String = selectedItem.DisplayText
        Dim Value As String = selectedItem.ItemValue
        '
        MsgBox("Selected = '" & Item & "', and the ID Value ='" & Value & "'")
        RunMMtest.Focus()
    End Sub

    Private Structure ComboBoxItem
        Dim DisplayText As String
        Dim ItemValue As String

        Public Sub New(ByVal _DisplayText As String, ByVal _ItemValue As String)
            DisplayText = _DisplayText
            ItemValue = _ItemValue
        End Sub

        Public Overrides Function ToString() As String
            Return DisplayText
        End Function
    End Structure

Open in new window

0
 
LVL 15

Expert Comment

by:x77
ID: 36505404
I think tommyBoy exposes a valid solution.

But do´nt says nothing about the reason to implements "ToString" on Structure ComboBoxItem.

You can manage the Format Event on ComboBox to Display apropiate text on a combobox for selected item.

But the easy solution is to use any class as item for ComboBox.
The Default Text you can see on a ComboBox.Text for selected Item is the Method "ToString" from Item Object.

Note. On this sample, Id (without "Id" prefix) always matches combobox' index
Then You do´nt need create Structure or class, but exposed solution is generic.
0
 
LVL 27

Assisted Solution

by:Ark
Ark earned 50 total points
ID: 36507109
Just to extend tommyBoy's solution a bit - you can use IEnumerable supported class (List(Of) for example to set combo DataSource):

 
Private cboItems as New List(Of MyData)
Sub FillCombo()
        cboItems.Clear
        For i As Integer = 0 To 19
            dim p1,p2,p3,p4 As String  
            p1="Data" & CStr(i)
            p2="Id" & CStr(i)) 
            p3="Whatever1" 
            p4="Whatever2" 
            cboItems.Add(New ComboBoxItem(p1, p2, p3, p4)
        Next (i)
        cboBookmarks.DisplayMember = "prop1"
        cboBookmarks.ValueMember = "prop2"
        cboBookmarks.DataSource = cboItems
    End Sub

   Private Class MyData
      Dim p1, p3, p4 As String
      Dim p2 As Integer

    Public Sub New(ByVal _p1 As String, ByVal _p2 As Integer, ByVal _p3 As String, ByVal _p4 As String)
        p1 = _p1 : p2 = _p2 : p3 = _p3 : p4 = _p4
    End Sub

    Public Property prop1() As String
        Get
            Return p1
        End Get
        Set(ByVal value As String)
            p1 = value
        End Set
    End Property

    Public Property prop2() As String
        Get
            Return p2
        End Get
        Set(ByVal value As String)
            p2 = value
        End Set
    End Property

    Public Property prop3() As String
        Get
            Return p3
        End Get
        Set(ByVal value As String)
            p3 = value
        End Set
    End Property

    Public Property prop4() As String
        Get
            Return p4
        End Get
        Set(ByVal value As String)
            p4 = value
        End Set
    End Property
    Public Overrides Function ToString() As String
        Return String.Format("Prop1={0}; Prop2={1}; Prop3={2}; Prop4={3}", p1, p2, p3, p4)
    End Function
End Class

Open in new window

0
 
LVL 27

Expert Comment

by:Ark
ID: 36507191
Oops,
cboItems.Add(New ComboBoxItem(p1, p2, p3, p4)
should be
cboItems.Add(New MyData(p1, p2, p3, p4))
0
 

Author Comment

by:FrankBabz
ID: 36512262
I thank all 3 of you for your time and replies.  I ran TommyBoy's code and excepting that cboBookmarks.Text = "item" does nothing... it worked great.  My problem, due to inexperience, is I am lost in it's apparent elegance and cannot understand it.  I had hoped to learn what is required to make a combobox work, and what I was doing wrong.  What parameter(s) is required for ADDing the ID and Data fields to a combobox?  What is comboboxitem actually generating?  Why is ToString being overridden?  What is the "new" sub purpose?

Thanks in advance for any help.
0
 
LVL 15

Assisted Solution

by:x77
x77 earned 50 total points
ID: 36512650
On Vb6, combo box item has Text an value properties.

On net the solution is most versatil:

  You can add any object to a combobox.
  Note that your object can contains many members an propertyes.

  ComboBox only show the ToString Method.
  But you can get each member from your class (class of Item Object).

  To get members or properties yo need cast the Item Object:

    Dim MyObject = Directcast(MyCombo.SelectedItem, MyClass)
    Debug.Print MyObject.member1.tostring

I asume all objects added to Combobox are from Type MyClass.

Note that you can add many objects to ComboBox from distinct Types, but then you need a Select - Case (Based on Object.GetType.name or TypeName) to cast the selecteditem.
0
Highfive Gives IT Their Time Back

Highfive is so simple that setting up every meeting room takes just minutes and every employee will be able to start or join a call from any room with ease. Never be called into a meeting just to get it started again. This is how video conferencing should work!

 
LVL 38

Accepted Solution

by:
Tom Beck earned 400 total points
ID: 36514072
My explanation:

Structures and classes are similar in that they both can contain methods, properties, etc. The difference is that structures are used for small, lightweight objects (like combo box items) and classes are generally used for larger objects that remain in memory for longer periods. Either one will work here.

The fact that VB.Net does not provide a more direct method for adding combo box items with multiple properties is just shortsightedness from Microsoft. Fortunately, as @x77 has pointed out, you can add many different types of objects with the ".Add" method. Here's where the structure comes in. The structure defines the object to be inserted, in this case with two string values. For each iteration in the for loop, a new instance of the object type "ComboBoxItem" is created and inserted using the index "i" to make each one unique.

My use of the variables DisplayText and ItemValue may be misleading. There's no correlation between the objects a combo box can hold and the name/value pairs you may be used to in an HTML dropdown selector. The two strings returned when a item is selected in your combo box are just the string values contained in the object "ComboBoxItem".

When an item is selected from the combo box and the SelectedIndexChanged event fires, it is necessary to cast the Selecteditem back into the exact object type it had when it was first inserted so you can retrieve the two string values associated with the object. This casting is done at this line: Dim selectedItem As ComboBoxItem = CType(cboBookmarks.SelectedItem, ComboBoxItem)

The "ToString" method of the object "ComboBoxItem" needs to be overridden because the default built-in "ToString" method will return the object's type in string form, not the text value. In other words, without the overridden "ToString" method, the combo box objects would say something like "MySolutionName.MyAppName+ComboBox". Try eliminating the "ToString" override and observe.

The "New" sub simply creates a new instance of the ComboBoxItem object each time it is called. The "new" sub is called on this line. cboBookmarks.Items.Add(New ComboBoxItem("Data" & Str(i), "Id" & Str(i)))

>>excepting that cboBookmarks.Text = "item" does nothing
Actually, I took this from your code and it does do something. It adds the word "item" as the first object in the combo box.
0
 

Author Closing Comment

by:FrankBabz
ID: 36514756
Thanks to all of you,
Frank
0
 

Author Comment

by:FrankBabz
ID: 36514778
>>excepting that cboBookmarks.Text = "item" does nothing
Actually, I took this from your code and it does do something. It adds the word "item" as the first object in the combo box.

Not sure where "first object" is, but it is not visible anywhere.

In vb.net I never found a combobox control.  Did you mean dropdownbox?  I did find a combobox in Access having column support that I liked a lot.  Are vb Windows Forms considered to be in vb.net?
0
 
LVL 38

Expert Comment

by:Tom Beck
ID: 36514916
The title of your question is "Combobox in a Windows Form". This can only mean a Windows Application. Combo boxes are not available to Web Applications.

Vb.net is a programming language that is available to both Windows Applications (Windows forms) and Web Applications. Vb.net should not be confused with asp.net. Asp.net is not a programming language but rather a term to describe the coding of web pages to take advantage of the .net framework. Web pages can be coded in vb.net, C# or J#.

Thanks for the points.
ComboBox.jpg
0
 

Author Comment

by:FrankBabz
ID: 36516252
You deserve more than I have offered because you have taken your valuable time for very little in return....  and I have learned a lot.

Thanks for the jpg, it depicts exactly what I surmised to be the "first object."  In my application, however, it does not display as you depicted.  My "first object" is blank.  In time, I may figure out why, and I will explain later.

God bless!
0
 

Author Comment

by:FrankBabz
ID: 36516487
Follow up:  
Changing the style from "dropdownlist" to either "simple" or "dropdown" will show/display the "first object" in the control.   I prefered "dropdownlist" only for appearance purposes with no real understanding that style may do more than change the apppearance of "first object."  I notice in the control's snippet of help for Style selection it says "Controls the appearance and functionality of the combo box."   Now I know one "functionality" change, but I know nothing more, and find this a strange and annoying function change.   Oh well????
0

Featured Post

How to run any project with ease

Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
- Combine task lists, docs, spreadsheets, and chat in one
- View and edit from mobile/offline
- Cut down on emails

Join & Write a Comment

Suggested Solutions

Title # Comments Views Activity
Help with deleting records in File2 when compared with File1 using VB.NET 7 55
GridDataView 6 44
Expando 4 34
Close word object 13 21
As more and more people are shifting to the latest .Net frameworks, the windows presentation framework is gaining importance by the day. Many people are now turning to WPF controls to provide a rich user experience. I have been using WPF controls fo…
Whether you've completed a degree in computer sciences or you're a self-taught programmer, writing your first lines of code in the real world is always a challenge. Here are some of the most common pitfalls for new programmers.
This is Part 3 in a 3-part series on Experts Exchange to discuss error handling in VBA code written for Excel. Part 1 of this series discussed basic error handling code using VBA. http://www.experts-exchange.com/videos/1478/Excel-Error-Handlin…
This video gives you a great overview about bandwidth monitoring with SNMP and WMI with our network monitoring solution PRTG Network Monitor (https://www.paessler.com/prtg). If you're looking for how to monitor bandwidth using netflow or packet s…

762 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

20 Experts available now in Live!

Get 1:1 Help Now