Question How do I add items to a combo box depending on what the user selects in the other?

techwiz24

Well-known member
Joined
Jun 2, 2010
Messages
51
Programming Experience
Beginner
I have 2 combo boxes. One is in a form called subcat_selector.vb

on the button Pick Sub Catagory.click event it shows the subcat_selector form. form there, the onload event:
VB.NET:
Dim button As DialogResult
        button = MsgBox("Please select the sub-catagory that the game you want to play is located in.", MsgBoxStyle.OkCancel, "Select a sub catagory")
        If button = Windows.Forms.DialogResult.OK Then
            For Each game As String In System.IO.Directory.GetDirectories("C:\gmtst")
                ComboBox1.Items.Add(game)
            Next
        Else
            Me.Close()
        End If
the user then clicks a confirm button, which hides the form. This section of the code works. it is the other section that I am having problems with

this is supposed to change the contents of combo box 1 in the main form:

VB.NET:
For Each game As String In System.IO.Directory.GetFiles(subcat_selector.ComboBox1.SelectedItem)
            ComboBox1.Items.Add(game)
        Next

but nothing shows up in the combo box in the main form...
 
Hi techwiz24,

I've actually done something similar to this recently. I would imagine that your comboboxes are pulling from a table. Could you please provide your table structure and from that, I'll be able to show code to populate the 2nd combobox based on what is selected in the first. It has to do with a relationship between the 2 tables that the comboboxes are linked to. I can give you an example. Say you have 2 tables, Order and Customer:

Order Customer
OrderID (PK) CustomerID(PK)
Item FName
Amount LName
CustomerID (FK) Address

The 2 tables are linked by CustomerID, which is a foreign key(FK) in the Order table and the primary key(PK) of the Customer table. So when you select an Order from the Order combobox from frmOrder, in order for the Customer combobox to populate with the corresponding customer, you would have to code as follows for the function that fills the customer combobox (we'll call it FillCustomerCombo) on the load event of the form (frmCustomerInfo) that has the customer combobox (which we'll say is frmCustomerInfo_Load):

frmCustomerInfo:
VB.NET:
Private Sub frmCustomerInfo_Load(ByVal sender As System.Object, ByVal CustomerID As System.EventArgs) Handles MyBase.Load

        conn.Open()
        Call FillCustomerCombo()
        conn.Close()
    End Sub

VB.NET:
Private Sub FillCustomerCombo()

        Dim sql2 As String = "Select distinct customer.Lname from customer order by LName asc"
        Dim cmdCorrespCustomer As New SqlCommand(sql, conn)

        Dim daCustomer As New SqlDataAdapter(cmdCorrespCustomer)

        Dim dsCustomerItems As New DataSet

        Dim dtDepot As New DataTable("Customer")

daCustomer.Fill(dsCustomerItems, "LName")

        Dim drCustomer As SqlDataReader = cmdCorrespCustomer.ExecuteReader

        While drCustomer.Read()
            cboCustomer.Items.Add(drCustomer("LName"))
        End While
        drCustomer.Close()

cmdCorrespCustomer.Cancel()
        cmdCorrespCustomer.Dispose()

I hope this helps. :)
 
What you are doing is attempting to pass values from one form to another. The fundamental thing to remember is that both are classes, classes are a blueprint for an object. In order to communicate information between 2 objects you need to have references.

I am going to say that we have 2 forms let's call them MainForm and SubForm. MainForm will have a button that will open an instance of SubForm and then we will do some work. SubForm will close and the selected values on SubForm will be transferred to MainForm. Well not transferred, we need to retrieve the values from the the SubForm object.

MainForm : ComboBox (cboSelectedItems), Button (btnOpenSubForm), Button (btnExit)

SubForm : ComboBox (cboSelectSubItems), Button (btnCloseSubForm)

VB.NET:
Public Class MainForm

    Private Sub btnOpenSubForm_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnOpenSubForm.Click

        'Here we create a new instance (an object) of the sub form
        Dim frmSub As New SubForm

        'Here we are using the object of the subform 
        If frmSub.ShowDialog(Me) = Windows.Forms.DialogResult.OK Then
            'we want to access the that property from the sub form.
            ' we must access the instance (object) of SubForm which is frmSub

            'Now we can assign this directly to the main form combo box
            cboSelectedItems.DataSource = frmSub.GetList

        End If

    End Sub

    Private Sub btnExit_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnExit.Click
        Me.Close()
    End Sub

    Private Sub cboSelectedItems_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cboSelectedItems.SelectedIndexChanged

    End Sub
End Class

VB.NET:
Public Class SubForm

    Private lValues As List(Of String)

    'This is a property that returns the list of selected values
    Public ReadOnly Property GetList() As List(Of String)
        Get
            Return lValues
        End Get
    End Property


    Private Sub btnCloseSubForm_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnCloseSubForm.Click

        'set the dialogresult to return from closing this form
        Me.DialogResult = Windows.Forms.DialogResult.OK

        Me.Close()

        'Or
        ' Me.Hide()
        ' If you hide though, you will need to reset lValues when the form shows (Show event)
    End Sub

    Private Sub cboSelectSubItems_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cboSelectSubItems.SelectedIndexChanged

        'if the selected value is not already in our list then add it
        ' This will fill the list that we will be able to pass back
        If Not lValues.Contains(cboSelectSubItems.SelectedValue.ToString()) Then
            lValues.Add(cboSelectSubItems.SelectedValue.ToString())
        End If

    End Sub
End Class
 
Ok.... so I changed the line:

VB.NET:
Private lValues As List(Of String)
to
VB.NET:
Private lValues As New List(Of String)
same error code...

hmm.... If I use the Try...Catch thingy, I can make my own error codes, but that doesn't solve it...
one of the suggestions appears to be what you said, if I hover w/ my mouse over the highlighted error, it says try the "New" thing that you suggested...

Sorry 'bout all of this, I am still learning, never "officially" learned VB.net, kinda self taught myself :D
 
The Main form:
VB.NET:
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        'Here we create a new instance (an object) of the sub form
        Dim subcat As New subcat_selector

        'Here we are using the object of the subform 
        If subcat.ShowDialog(Me) = Windows.Forms.DialogResult.OK Then
            'we want to access the that property from the sub form.
            ' we must access the instance (object) of SubForm which is frmSub

            'Now we can assign this directly to the main form combo box
            ComboBox1.DataSource = subcat.cboSelectSubItems.SelectedItem

        End If

    End Sub


The Sub Form:
VB.NET:
Public Class subcat_selector
    Private Sub subcat_selector_Load(ByVal sender As System.Object, ByVal e As System.EventArgs)
            For Each game As String In System.IO.Directory.GetDirectories("C:\gmtst\")
                cboSelectSubItems.Items.Add(game)
            Next
    End Sub
    Private lValues As New List(Of String)

    'This is a property that returns the list of selected values
    Public ReadOnly Property GetList() As List(Of String)

        Get
            Return lValues
        End Get

    End Property

    Private Sub btnCloseSubForm_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        If Not lValues.Contains(cboSelectSubItems.SelectedValue.ToString()) Then
            lValues.Add(cboSelectSubItems.SelectedValue.ToString())
        End If
        'set the dialogresult to return from closing this form
        Me.DialogResult = Windows.Forms.DialogResult.OK
        Me.Close()


        'Or
        ' Me.Hide()
        ' If you hide though, you will need to reset lValues when the form shows (Show event)
    End Sub
End Class

the error is produced in the sub form as soon as I click an item that's in the combo box, the debugger highlights this line:
VB.NET:
lValues.Add(cboSelectSubItems.SelectedValue.ToString())

-----EDIT-----
I musta done something wrong, because now nothing is in the combo box...
 
I am pretty sure I know what is going on now.

A combo box can have display text (DisplayMember) and value text (ValueMember) so that way you can show something that looks purty but the ugliness is hidden in the selected value. You don't have a value just the display text, and we were looking for a value.

VB.NET:
lValues.Add(cboSelectSubItems.SelectedValue.ToString())

in your case (any case with a single value in the Items) should be

VB.NET:
lValues.Add(cboSelectSubItems.SelectedItem.ToString())
 
Thank You!!!!!

I changed my rout a little bit, but it works now:

Part1:
VB.NET:
For Each subcat As String In System.IO.Directory.GetDirectories("C:\gmtst\")
            ComboBox2.Items.Add(subcat)
        Next

ComboBox2 is then hidden and then:
VB.NET:
Private Sub ComboBox2_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ComboBox2.SelectedIndexChanged
        ComboBox2.Hide()
        ComboBox1.Show()
        Dim findgames As New List(Of String)
        For Each game As String In System.IO.Directory.GetFiles(ComboBox2.SelectedItem.ToString())
            ComboBox1.Items.Add(game)
        Next
    End Sub

SUCCESSSSS!!!!!!!!

thank you! I will be sure to mention you in the publication of my program if this idea ever takes off!!!
 
Back
Top