Programming for Everybody: How to populate combobox based on another combobox selection item in vb.net With Source Code

How to populate combobox based on another combobox selection item in vb.net With Source Code



Imports System.Data.SqlClient

Public Class Form2

    Private Sub Form2_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load

        Dim constr1 As String = "data source=.; initial catalog=names;integrated security=true"

        Using con1 As SqlConnection = New SqlConnection(constr1)


            Using sda1 As SqlDataAdapter = New SqlDataAdapter(" Select id,name from table1", con1)


                Dim dt As DataTable = New DataTable

                sda1.Fill(dt)



                Dim row As DataRow = dt.NewRow()

                row(0) = 0

                row(1) = "Select"

                dt.Rows.InsertAt(row, 0)

                ComboBox1.DataSource = dt

                ComboBox1.DisplayMember = "name"

                ComboBox1.ValueMember = "id"


            End Using


        End Using






    End Sub

    Private Sub ComboBox1_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ComboBox1.SelectedIndexChanged


        Dim con1 As SqlConnection = New SqlConnection("Data source=.\;initial catalog=names;integrated security=true")

        con1.Open()
        Dim strsql As String
        strsql = "Select tel from table1 where name='" + ComboBox1.Text + "'"

        Dim cmd As New SqlCommand(strsql, con1)

        Dim myreader As SqlClient.SqlDataReader

        myreader = cmd.ExecuteReader

        ComboBox2.Items.Clear()
        While myreader.Read


            ComboBox2.Items.Add(myreader("tel"))


        End While


        con1.Close()


    End Sub
End Class

No comments:

Post a Comment