VB.net从Mysql将数据加载到datagridview

时间:2015-04-16 11:58:56

标签: mysql vb.net winforms datagridview

我有一个datagridview,我已经在那里放了3列(通过设计),但是当我运行这个代码时,它会添加另外3列,并且数据会加载到那些新创建的列中。它怎么能只从我做的列加载数据?

编辑:第一列和第二列是文本框,第三列是组合框。

代码处于表单加载状态:

    Dim sqlDataAdapter As New MySqlDataAdapter
    Dim dt As New DataTable
    Dim bSource As New BindingSource

    Try
        sqlconn.Open()
        Dim query As String
        query = "SELECT * FROM tbl_subject ORDER BY yearlevel, code"
        sqlcommand = New MySqlCommand(query, sqlconn)
        sqlDataAdapter.SelectCommand = sqlcommand
        sqlDataAdapter.Fill(dt)
        bSource.DataSource = dt
        datagrid_Subject.DataSource = bSource
        sqlDataAdapter.Update(dt)

        sqlconn.Close()
    Catch ex As Exception
        MessageBox.Show(ex.Message)
    Finally
        sqlconn.Dispose()
    End Try

2 个答案:

答案 0 :(得分:1)

DataGridView的列具有属性DataPropertyName,将其值设置为sql查询中的列名。
这将显示预定义列中的数据

正如@Icepickle在评论集datagrid_Subject.AutoGenerateColumns = False中所说的那样 这将阻止datagridview为sql查询的SELECT语句中使用的所有字段生成列

答案 1 :(得分:0)

只需转到工具箱并拖放datagridview, 在属性上命名为dgvSubject 使用上面代码的示例将如下所示;

Dim sqlDataAdapter As New MySqlDataAdapter     Dim dt As New DataTable     Dim bSource As New BindingSource

Try
    sqlconn.Open()
    Dim query As String
    query = "SELECT * FROM tbl_subject ORDER BY yearlevel, code"
    sqlcommand = New MySqlCommand(query, sqlconn)
    sqlDataAdapter.SelectCommand = sqlcommand
    sqlDataAdapter.Fill(dt)
    bSource.DataSource = dt
    dgvSubject.DataSource = bSource
    sqlDataAdapter.Update(dt)

    sqlconn.Close()
Catch ex As Exception
    MessageBox.Show(ex.Message)
Finally
    sqlconn.Dispose()
End Try