Rekcs Rekcs - 7 months ago 27
Vb.net Question

Populate a combobox and get results on DataGridView

I am getting results from the database to populate on the Combobox and that's everything right. What I am trying to do next is after chose something from that Combobox it'll show on the DataGridView with some info of what I selected from CB.

This is the code that I am using right now

SQLCon = New SqlConnection
SQLCon.ConnectionString = "....."
Try
SQLCon.Open()
Dim Query As String
Query = "SELECT Filetype FROM infofile GROUP BY Filetype"
SqlCmd = New SqlCommand(Query, SQLCon)
SQLDataReader = SqlCmd.ExecuteReader
While SQLDataReader.Read
Dim fileType = SQLDataReader.GetString(0)
DataGridView1.DataSource = ComboBox1.Items.Add(fileType)
End While
SQLCon.Close()
Catch ex As SqlException
MsgBox(ex.Message)
Finally
SQLCon.Dispose()
End Try

Answer

First Fill ComboBox with your code like :

SQLCon = New SqlConnection
SQLCon.ConnectionString = "....."
Try
    SQLCon.Open()
    Dim Query As String
    Query = "SELECT Filetype FROM infofile GROUP BY Filetype"
    SqlCmd = New SqlCommand(Query, SQLCon)
    SqlDataReader = SqlCmd.ExecuteReader
    While SqlDataReader.Read
        Dim fileType = SqlDataReader.GetString(0)
        ComboBox1.Items.Add(fileType)
    End While
    SQLCon.Close()
Catch ex As SqlException
    MsgBox(ex.Message)
Finally
    SQLCon.Dispose()
End Try

And create Function that return Data from Database to DataGridView where ComboBox change data like this :

Private Sub ComboBox1_SelectedIndexChanged(sender As Object, e As EventArgs) Handles ComboBox1.SelectedIndexChanged
    DataGridView1.DataSource = FillDataGridView(ComboBox1.Text)
End Sub

Function FillDataGridView(valueComboBox As String) As DataTable
    SQLCon = New SqlConnection
    SQLCon.ConnectionString = "....."
    Try
        SQLCon.Open()
        Dim Query As String
        Query = "SELECT Filetype FROM infofile where Filetype=@Filetype"
        SqlCmd = New SqlCommand(Query, SQLCon)
        SqlCmd.Parameters.Add("@Filetype", SqlDbType.VarChar).Value = valueComboBox
        Dim adapter As New SqlDataAdapter(SqlCmd)
        Dim table As New DataTable
        adapter.Fill(table)
        SQLCon.Close()
        Return table
    Catch ex As SqlException
        MsgBox(ex.Message)
    Finally
        SQLCon.Dispose()
    End Try
End Function

You can change query to give more field as you like