Go Premium for a chance to win a PS4. Enter to Win

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 769
  • Last Modified:

Combobox in windows Form

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
FrankBabz
Asked:
FrankBabz
  • 5
  • 3
  • 2
  • +1
3 Solutions
 
Tom BeckCommented:
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
 
x77Commented:
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
 
ArkCommented:
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
Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
ArkCommented:
Oops,
cboItems.Add(New ComboBoxItem(p1, p2, p3, p4)
should be
cboItems.Add(New MyData(p1, p2, p3, p4))
0
 
FrankBabzAuthor Commented:
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
 
x77Commented:
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
 
Tom BeckCommented:
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
 
FrankBabzAuthor Commented:
Thanks to all of you,
Frank
0
 
FrankBabzAuthor Commented:
>>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
 
Tom BeckCommented:
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
 
FrankBabzAuthor Commented:
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
 
FrankBabzAuthor Commented:
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

Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

  • 5
  • 3
  • 2
  • +1
Tackle projects and never again get stuck behind a technical roadblock.
Join Now