hi all! i have two combo box in my program

one has the subteam for example if you click the 1st combo box, the items would be
A1
A2
A3
A4
A5
what i want to happen is that if i chose A1 only the members of team A1 would appear in my combo box2. and by that, you need an sql statement. but how do i code that? can someone help me?

Dani AI

Generated

Brief summary and what's missing from the thread: the goal is to filter ComboBox2 by the SubTeam selected in ComboBox1. Several contributors already fixed basic issues — correctly pushed parameterized queries, and pointed out the missing SqlClient imports and declarations, and showed a working reader loop — but two recurring problems remained: (a) SelectedIndexChanged firing during form load and (b) duplicate names because the same person can appear in multiple ticket rows.

A more robust pattern is: use parameterized commands inside Using blocks (ensures disposal), fill a DataTable with a data adapter, deduplicate in-memory if desired, and bind that DataTable as the ComboBox2 DataSource. Binding avoids manual Items.Add loops and is faster and less error-prone. The example below illustrates the pattern (adapt connection string, column names and sizes as needed):

' Imports System.Data.SqlClient required at top of file

Private Sub LoadMembersForSubTeam(subTeam As String)
    Using cn As New SqlConnection(MyConnString)
        Using da As New SqlDataAdapter("SELECT [user] FROM finaltickettable WHERE SubTeam = @s", cn)
            da.SelectCommand.Parameters.Add("@s", SqlDbType.VarChar, 50).Value = subTeam.Trim()
            Dim dt As New DataTable()
            da.Fill(dt)
            Dim distinctUsers As DataTable = dt.DefaultView.ToTable(True, "user")
            ComboBox2.BeginUpdate()
            ComboBox2.DataSource = distinctUsers
            ComboBox2.DisplayMember = "user"
            ComboBox2.ValueMember = "user"
            ComboBox2.EndUpdate()
        End Using
    End Using
End Sub

Prevent the control from reacting during form initialization:

Private loading As Boolean = True
' set loading = False after ComboBox1 is populated
Private Sub ComboBox1_SelectedIndexChanged(...) Handles ComboBox1.SelectedIndexChanged
    If loading Or ComboBox1.SelectedIndex < 0 Then Return
    LoadMembersForSubTeam(ComboBox1.Text)
End Sub

Troubleshooting checklist (concise): confirm the connection string and test the SQL in SSMS; bracket reserved column names like [user]; trim/case-match SubTeam values; surface exceptions (MsgBox or logging) to see failures; prefer typed parameters over concatenation or AddWithValue where possible; use server-side DISTINCT if preferred but client-side deduplication via DefaultView works well when filtering from an existing resultset. This ties together the thread’s fixes while giving a safer, maintainable approach.

Recommended Answers

All 36 Replies

Hi,
In the selectedIndexChanged event of the first combo box you determine the selected index and include that into your SQL string.

string selectedTeam = comboBox1.SelectedItem.ToString();
string sql = "SELECT * FROM yourTable WHERE team = ?selectedTeam;";
cmd.CommandText = sql;
cmd.Parameters.Add("?selectedTeam", MySqlDbType.Varchar);
cmd.Parameters["?selectedTeam"].Value = selectedTeam;

I'm assuming you have a command object called cmd of course. After that open your connection, execute the command, catch the results in a dataTable or reader and import into the second comboBox. I have made so assumptions about your database table design too of course.

commented: c# in vb.net forum :( -3

hi hericles!
is that for vb.net code? can you give me the full code?

Thats c# (i'm always making that mistake)...
I'll post something more complete in a couple of hours. I'm going to assume your database is set up with a table of teams, a table of players and a table that links the two. I hope thats accurate.

Try this,

Conn.Open()
   Dim str_query As String = "select * from tableName where Field=" & Combo1.Text &"
   cmd = New SqlCommand(str_query, Conn)
   dr = cmd.ExecuteReader
   Combo2.Items.Clear()  
   Do While dr.Read()
       Combo2.Items.Add(dr.Item("Fieldname"))
   Loop
   dr.Close()
 Conn.Close()

hi bhagawatshinde!
is that vb.net?

hericles,
ok i'll wait

well the dr part has an error cause its not declared. if i declare dr what kind of declaration should i use?

Type 'SqlCommand' is not defined.
Name 'dr' is not declared.
Name 'dr' is not declared.
Name 'dr' is not declared.
Name 'dr' is not declared.

those are the errors

use namespace as
Imports System.Data.SqlClient
Imports System.Data.Sql

use this declaration,
Dim cmd As New SqlCommand
Dim dr as new SqlDataReader
Dim da As New SqlDataAdapter

Import-----

Imports System.Data.SqlClient
Imports System.Data.Sql
Create an object------
   Public dr As SqlDataReader
    Public cmd As New SqlCommand

Import the following on top of the page

Imports System.Data.Sql
Imports System.Data.SqlClient

and declare following

Dim cmd As New SqlCommand
 Dim dr As SqlDataReader

Dim dr As System.Data.SqlDataReader

He has left out the initial declaration of the command object and the data reader. Add this:

Dim cmd As New SqlCommand()
cmd = New SqlCommand(str_query, Conn)
Dim dr As New DataReader()
dr = cmd.ExecuteReader

hericles are you still there?

Member Avatar for Member #857553

I'm assuming I saw your thread on code project.

This should do what your doing.

I used SqlCe as the database if using .mdf db then change the variables to SqlCommand instead of SqlCeCommand and so on.

Imports System.Data.SqlServerCe
Imports System.Data.SqlClient 'if using .mdf
Public Class Form2
    Private Const ConnectionString As String = "Your Connection String"

    Private Sub ComboBox1_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ComboBox1.SelectedIndexChanged
        If TypeOf ComboBox1.SelectedItem Is String Then

            Dim Connection As New SqlCeConnection(ConnectionString)
            Dim Command As SqlCeCommand = Connection.CreateCommand
            Dim Reader As SqlCeDataReader = Nothing

            Command.CommandText = "Select *" & vbCrLf & _
                                  "From finaltickettable" & vbCrLf & _
                                  "Where Subteam = @SubTeam"
            Command.Parameters.AddWithValue("@SubTeam", CStr(ComboBox1.SelectedItem))

            ComboBox2.BeginUpdate()
            ComboBox2.Items.Clear()
            Try
                Connection.Open()
                Reader = Command.ExecuteReader
                Do While Reader.Read
                    ComboBox2.Items.Add(CStr(Reader("YourColumnName")))
                Loop

            Catch ex As Exception
            Finally
                Connection.Dispose()
                Command.Dispose()
                'dispose may not be available with sqldatareader
                If Reader IsNot Nothing Then Reader.Dispose()
            End Try

            ComboBox2.EndUpdate()
        End If
    End Sub

End Class

hi thanks for your reply unhnd exception! i changed it to sqlcommand but its still error

Dim Connection As New SqlConnection(ConnectionString)
Dim Command As SqlCommand = Connection.CreateCommand
Dim Reader As SqlDataReader = Nothing


the bold part are the error

Member Avatar for Member #857553

Did you add imports System.Data.SqlClient to the top of your form??

i just imported it thanks! i have an error on

Dim Connection As New SqlConnection(ConnectionString)

should i place there my connection string?

Member Avatar for Member #857553

Did you add a global ConnectionString variable like my original post depicted?

Did you set the ConnectionString variable to the connection string of your db?

hi. sorry for that i already fixed that. theres no error anymore but whenever i execute my program if i select A1 theres nothing on my combo box2

Member Avatar for Member #857553

From my original post. Add this under Catch ex as exception

Try
Catch ex as exception
   'add this
    MsgBox(ex.Message)
finally

See what errors are coming up. If no errors then you need to check your table.

Let me know how that goes.

For [Type 'SqlCommand' is not defined.] error, u got to do

Imports System.Data.SqlClient

For [Name 'dr' is not declared. ] error, do

Dim dr as SqlDataReader = cmd.ExecuteReader
Member Avatar for Member #857553

: We're past that.

hi Unhnd Exception! its fixed but i still got one problem though. in my record, name jake held 3 tickets so he has 3 records in my database. he is in team A4. whenever i choose A4 his name appears thrice. how will i fix that?

Member Avatar for Member #857553

You need to change your Select statement to add Distinct
.

From my orignal code; Change to

Command.CommandText = "Select Distinct *" & vbCrLf & _
                        "From finaltickettable" & vbCrLf & _
                        "Where Subteam = @SubTeam"

@BlurrieBlue: Where past that.

Oops.. When i post it, the page refresh and many other comments and solution had been posted.. I guess I'm slow XD

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.