我从数据库中获取结果以填充Combobox并确保一切正常。接下来我要做的就是从这个Combobox中选择一些东西,然后在DataGridView上显示我从CB中选择的一些信息。
这是我现在正在使用的代码
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
答案 0 :(得分:0)
首先使用您的代码填充ComboBox
:
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
创建Function
,将数据从数据库返回到DataGridView
,其中ComboBox
更改数据如下:
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 = "....."
Dim table As New DataTable
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)
adapter.Fill(table)
SQLCon.Close()
Return table
Catch ex As SqlException
MsgBox(ex.Message)
Return table
Finally
SQLCon.Dispose()
End Try
End Function
您可以根据需要更改查询以提供更多字段