我有一个包含4个标签的表单,每个标签包含一个datagridview。我想用我的数据库中的不同表填充每个这些网格,但查询结果不断累积,直到最终表包含4个查询的结果。 这是我的代码:
Try
mysqlconn.Open()
Dim query As String
query = "SELECT* from venue"
command = New MySqlCommand(query, mysqlconn)
SDA.SelectCommand = command
SDA.Fill(dbdataset)
bsource.DataSource = dbdataset
DataGridView1.DataSource = bsource
SDA.Update(dbdataset)
query = "SELECT* FROM Decoration"
command = New MySqlCommand(query, mysqlconn)
SDA.SelectCommand = command
SDA.Fill(dbdataset)
bsource.DataSource = dbdataset
DataGridView2.DataSource = bsource
SDA.Update(dbdataset)
query = "SELECT* FROM food_drink"
command = New MySqlCommand(query, mysqlconn)
SDA.SelectCommand = command
SDA.Fill(dbdataset)
bsource.DataSource = dbdataset
DataGridView3.DataSource = bsource
SDA.Update(dbdataset)
query = "SELECT* FROM Entertainment"
command = New MySqlCommand(query, mysqlconn)
SDA.SelectCommand = command
SDA.Fill(dbdataset)
bsource.DataSource = dbdataset
DataGridView4.DataSource = bsource
mysqlconn.Close()
Catch ex As MySqlException
MsgBox(ex.Message)
Finally
mysqlconn.Dispose()
End Try
当我更改它以便每个查询都有自己的数据表(dbdataset)时,我只是获取所有显示最终查询结果的datagridviews。
Try
mysqlconn.Open()
Dim query As String
query = "SELECT* from venue"
command = New MySqlCommand(query, mysqlconn)
SDA.SelectCommand = command
SDA.Fill(dbdataset1)
bsource.DataSource = dbdataset1
DataGridView1.DataSource = bsource
SDA.Update(dbdataset1)
query = "SELECT* FROM Decoration"
command = New MySqlCommand(query, mysqlconn)
SDA.SelectCommand = command
SDA.Fill(dbdataset2)
bsource.DataSource = dbdataset2
DataGridView2.DataSource = bsource
SDA.Update(dbdataset2)
query = "SELECT* FROM food_drink"
command = New MySqlCommand(query, mysqlconn)
SDA.SelectCommand = command
SDA.Fill(dbdataset3)
bsource.DataSource = dbdataset3
DataGridView3.DataSource = bsource
SDA.Update(dbdataset3)
query = "SELECT* FROM Entertainment"
command = New MySqlCommand(query, mysqlconn)
SDA.SelectCommand = command
SDA.Fill(dbdataset4)
bsource.DataSource = dbdataset4
DataGridView4.DataSource = bsource
SDA.Update(dbdataset4)
mysqlconn.Close()
Catch ex As MySqlException
MsgBox(ex.Message)
Finally
mysqlconn.Dispose()
End Try
答案 0 :(得分:1)
你可以缩小代码的方式。通过使用分号分隔命令在命令中使用多个查询,每个查询将加载到DataTable中。然后将网格绑定到正确的数据表:
Try
mysqlconn.Open()
Dim query As String
query = "SELECT* from venue;SELECT* FROM Decoration;SELECT* FROM food_drink;SELECT* FROM Entertainment;"
SDA.SelectCommand = New MySqlCommand(query, mysqlconn)
SDA.Fill(dbdataset)
DataGridView1.DataSource = dbdataset.Tables(0)
DataGridView2.DataSource = dbdataset.Tables(1)
DataGridView3.DataSource = dbdataset.Tables(2)
DataGridView4.DataSource = dbdataset.Tables(3)
mysqlconn.Close()
Catch ex As MySqlException
MsgBox(ex.Message)
Finally
mysqlconn.Dispose()
End Try
您还可以创建4个绑定源并绑定到这些绑定源而不是直接绑定到表。您还应该处理连接和命令。