In my windows form, I have a combo box which is populated with (part code)values from my database and I'm finding it hard to set each equivalent (part name)value to a text box which is in the same table. I was able to populate combo box values using the code below but I cannot work on text box field. Can anyone help with this? Thank you in advance. :)

If cmbProcess.SelectedIndex = "0" Then
                Dim strSQL As String
                strSQL = "select PartCode from tblINKPROCESSING"
                Dim da As New SqlDataAdapter(strSQL, con)
                Dim ds As New DataSet
                da.Fill(ds, "tblINKPROCESSING")

                With cmbPCode
                    .DataSource = ds.Tables("tblINKPROCESSING")
                    .DisplayMember = "PartCode"
                    .ValueMember = "PartCode"
                    .SelectedIndex = -1
                End With
            Catch ex As Exception
                MessageBox.Show("Error while connecting to SQL Server." & ex.Message)
            End Try
        End If

Recommended Answers

All 3 Replies


I am assuming that PartCode is unique and that when you want to get the PartName, this will occur when you choose a PartCode from the combo box?

If the assumption above is correct, then you could do something like the following in the SelectedIndexChanged event of the combo box:

Dim selectStatement As String = "SELECT PartName FROM tblINKPROCESSING WHERE PartCode = @PartCode"

Using connection As New SqlConnection(connectionString)


    Using Command As New SqlCommand(selectStatement, connection)

        Command.Parameters.AddWithValue("@PartCode", cmbPCode.Text)

        Dim reader As SqlDataReader = Command.ExecuteReader

        Do While reader.Read()

            txtPName.Text = reader("PartName").ToString


    End Using

End Using


You are going to have a problem with

If cmbProcess.SelectedIndex = "0" Then

because cmbProcess.SelectedIndex is numeric and you are comparing it to a string. Try

If cmbProcess.SelectedIndex = 0 Then

Got it! It worked.

Djjeavons Thank you very much for your help! Much appreciated. :) :)

Reverend Jim .. thank you also for sharing some points to consider. :)

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.