我的一个 Windows 窗体上有一个 Datagridview,我打算让用户从组合框下拉菜单中选择一个查询,单击一个按钮,然后查询结果将显示在 datagridview 上。
That is all working properly, however when a different query is selected and submitted, the datagridview displays additional empty columns used by the previously selected query.
阻止这种情况发生的最好方法是什么?这是基于datagridview本身吗?或我的子程序连接到数据库并执行查询
我尝试清除数据表(在查询子例程中使用)和数据网格视图的列,但这并没有解决问题。
我用按钮清除datagridview的各种尝试(尝试了各种组合):
Private Sub btnclearquery_Click(sender As System.Object, e As System.EventArgs) Handles btnclearquery.Click
mysql.qrydata.Clear()
DataGridViewqry.DataSource = Nothing
DataGridViewqry.Columns.Clear()
DataGridViewqry.Rows.Clear()
End Sub
我执行查询的子程序(在另一个代码文件中引用。当用户从组合框中选择查询时,使用 select case 填充 sqlquery 字符串):
Public qrysqlconn As MySqlConnection
Public qrycommand As New MySqlCommand
Public qryadapter As New MySqlDataAdapter
Public qrydata As New DataTable
Public qrysql As String
Public Sub doquery(ByVal sqlquery As String)
qrysqlconn = New MySqlConnection
qrysqlconn.ConnectionString = "server=localhost;" _
& "user id=root;" _
& "password=W1nd0ws;" _
& "database=hystest"
qrysql = sqlquery
Try
qrysqlconn.Open()
qrydata.Clear()
qrycommand.Connection = qrysqlconn
qrycommand.CommandText = qrysql
qryadapter.SelectCommand = qrycommand
qryadapter.Fill(qrydata)
queries.DataGridViewqry.DataSource = qrydata
queries.DataGridViewqry.FirstDisplayedScrollingRowIndex = queries.DataGridViewqry.RowCount - 1
Catch myerror As MySqlException
MessageBox.Show("Database error: " & myerror.Message)
Finally
qrysqlconn.Close()
qrysqlconn.Dispose()
End Try
End Sub