在vb.net中将datagrid视图连接到数据库

时间:2013-04-15 21:08:15

标签: mysql vb.net

好的,我试图使用datagrid视图显示我的MYSQL数据库中的所有内容。但我得到的是不起作用,有人可以用我的代码帮助我

    Public Sub dataview()
    DataGridView1.DataSource = ""
    Dim bindingSource1 As New BindingSource()
    Try
    Dim cmd As New MySqlCommand("SELECT * FROM upload", db_con)

    With Me.DataGridView1
        .AutoGenerateColumns = True

        bindingSource1.DataSource = cmd
        .DataSource = bindingSource1

        .AutoSizeRowsMode = DataGridViewAutoSizeRowsMode.DisplayedCellsExceptHeaders
        .BorderStyle = BorderStyle.Fixed3D
        .EditMode = DataGridViewEditMode.EditOnEnter
    End With
        DataGridView1.DataSource = bindingSource1
    Catch ex As Exception
        MessageBox.Show("something went wrong")
    End Try

2 个答案:

答案 0 :(得分:0)

您不能简单地将MySqlCommand传递给BindingSource 您应该使用MySqlDataAdapter类型的对象来获取命令并填充DataSet / DataTable。 DataTable / DataSet应该用作bindingSource1

的DataSource
Dim cmd As New MySqlCommand("SELECT * FROM upload", db_con)
Dim da = New MySqlDataAdapter (cmd)
Dim dt = New DataTable()
da.Fill(dt)
bindingSource1.DataSource = dt ' here assign the DataTable'

With Me.DataGridView1
    .AutoGenerateColumns = True
    .DataSource = bindingSource1
    .....
End With

答案 1 :(得分:0)

Public Sub dataview()
DataGridView1.DataSource = ""
Dim bindingSource1 As New BindingSource()
Try
Dim cmd As New MySqlCommand("SELECT * FROM upload", db_con)

With Me.DataGridView1
    .AutoGenerateColumns = True

    bindingSource1.DataSource = cmd
    .DataSource = bindingSource1

    .AutoSizeRowsMode = DataGridViewAutoSizeRowsMode.DisplayedCellsExceptHeaders
    .BorderStyle = BorderStyle.Fixed3D
    .EditMode = DataGridViewEditMode.EditOnEnter
End With
    DataGridView1.DataSource = bindingSource1
Catch ex As Exception
    MessageBox.Show("something went wrong")
End Try

尝试这个^^