Search code examples
sqldatabasevb.netcomboboxtextbox

SQL Column to TextBox (from ComboBox)


I have managed to add data into a ComboBox from a column out of my SQL table, but I need the rows from across to display in the rest of the textboxes. (I hope I have worded this correctly).

Here is my code currently:

Imports System.Data.SqlClient


Public Class Form1

    Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load

        Dim con As New SqlConnection("Data Source=xxxx;Initial Catalog=ltLeavers;Integrated Security=True")

        Dim da As New SqlDataAdapter("SELECT * FROM dbo.mytable", con)
        Dim dt As New DataTable
        da.Fill(dt)
        ComboBox1.DisplayMember = "DISPLAY_NAME"
        ComboBox1.DataSource = dt

    End Sub

The above works with no issues, all of the items add into the ComboBox but I need the corresponding rows from the other two columns which are EMAIL_ADDRESS and DEPARTMENT to add into TextBoxes from what is selected in the ComboBox.


Solution

  • Under the SelectedIndex_Changed event of the ComboBox; Enter the following code.

    Dim dt As New DataTable
    Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
    
        Dim con As New SqlConnection("Data Source=xxxx;Initial Catalog=ltLeavers;Integrated Security=True")
    
        Dim da As New SqlDataAdapter("SELECT * FROM dbo.mytable", con)
        da.Fill(dt)
        ComboBox1.DisplayMember = "DISPLAY_NAME"
        ComboBox1.DataSource = dt
    
    End Sub
    Private Sub ComboBox1_SelectedIndexChanged(sender As Object, e As EventArgs) Handles ComboBox1.SelectedIndexChanged
        Textbox1.Text = CStr(dt.Rows(ComboBox1.SelectedIndex)("EMAIL_ADDRESS"))
        Textbox2.Text = CStr(dt.Rows(ComboBox1.SelectedIndex)("DEPARTMENT"))
    End Sub
    

    You Will need to declare the data table dt outside your form's load event so it can be visible to the SelectedIndex_Changed event of the combo box.