turn and fall
turn and fall

Reputation: 15

Visual Basic- Using combo boxes to fill data from Access tables to text boxes

I'm currently making a form that is for data entry for new "Orders" and was wondering how I could use a combo box to select an already filled out order details from an Access table so that the information is sent back to the text boxes for review or modification.

I might not have explained what I want very clearly so I have added a picture (Gyazo link) below of the form, as you can see at the top there is the combo box. I want all the other text boxes to be filled with the existing data if it's selected from the combo box, but for the life of me can't think how I would do it.

https://gyazo.com/5e1c8df5311ce75c421bbe0e9c4ccd0a

Any help is greatly appreciated, thanks in advance!

Upvotes: 0

Views: 1268

Answers (1)

Chris Stack
Chris Stack

Reputation: 23

In the Code behind you would have to use the combobox's 'SelectedIndexChanged' Event. Inside that function you can change the textbox text to what ever you like. For Example if we have a combox called cmbTest and a text box called txtTest:

Private Sub cmbTest_SelectedIndexChanged(sender As Object, e As EventArgs) Handles cmbTest.SelectedIndexChanged
    txtTest.Text = "whatever text you want"
End Sub

You could use a select statment to decide what text to use based on the combobox e.g:

Private Sub cmbTest_SelectedIndexChanged(sender As Object, e As EventArgs) Handles cmbTest.SelectedIndexChanged

    Select Case cmbTest.SelectedIndex
        Case 1
            txtTest.Text = "The Selected index is 1"
        Case 2
            txtTest.Text = "The Selected index is 2"
        Case 3
            txtTest.Text = "The Selected index is 3"
    End Select

End Sub

You could do something along these lines to access the data in the access database (obviously you will need to replace the sql statement with whatever tables / columns you have in your access db):

    Dim dt As New DataTable
    Dim cn As New OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\PATH_TO_MDB_FILE\db1.mdb;")

    Try

        cn.Open()
        Dim Str As String = "SELECT * FROM yourTableName WHERE columnName = '" & ComboBox1.SelectedValue.ToString & "'" ' Or whatever SQL statement you want
        Dim cmd As New OleDbCommand(Str, cn)
        dt.Load(cmd.ExecuteReader())
    Catch
        'handle error
    End Try
    cn.Close()

You can then use the datatable to access the text to put into the textboxes e.g:

txtTest.Text = dt.Rows(0).Item("ColumnName").ToString()

I hope that helps, and that I understood what you want.

Upvotes: 1

Related Questions