使用DataAdapter更新DataGridView

时间:2017-11-09 22:42:24

标签: mysql vb.net datagridview dataadapter

我无法从我的DataGridView中获得更改。

使用Visual Studio 2015
带有MySQL数据库的Windows窗体

Imports MySql.Data.MySqlClient

Public Class Form2
    Dim dt As DataTable
    Dim da As MySqlDataAdapter
    Dim myCommandBuilder As MySqlCommandBuilder
    Private command As MySqlCommand = Nothing

    Private Sub Form2_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        Dim serverString As String = "server = localhost; user id = root;  database=tickedoff"
        Dim con As MySqlConnection = New MySqlConnection(serverString)
        DataGridView1.Columns.Clear()

        If con.State = ConnectionState.Closed Then
            con.Open()
        End If

        Dim cmd As MySqlCommand = New MySqlCommand
        Dim insertCom As String
        Dim updateCom As String
        insertCom = "SELECT * FROM Pet"
        updateCom = "UPDATE `tickedoff`.`pet` SET petName = petName, species = species,
            breed = breed, DOB = DOB, gender = gender, weight = weight, customerID = customerID WHERE `pet`.`petID` =petID ;"

        cmd.CommandType = CommandType.Text
        cmd.CommandText = insertCom
        cmd.Connection = con
        Dim uCmd As MySqlCommand = New MySqlCommand
        uCmd.CommandType = CommandType.Text
        uCmd.CommandText = updateCom
        uCmd.Connection = con
        da = New MySqlDataAdapter()
        da.SelectCommand = cmd
        da.UpdateCommand = uCmd
        dt = New DataTable

        da.Fill(dt)
        da.Fill(dt)
        With DataGridView1
            .AutoGenerateColumns = True
            .DataSource = dt
        End With
        cmd.Dispose()
        cmd = Nothing
        con.Close()
        con.Dispose()
    End Sub

    Private Sub btnUpdate_Click(sender As Object, e As EventArgs) Handles btnUpdate.Click
        Try
            DataGridView1.EndEdit()
            da.Update(dt)
        Catch ex As Exception
            MessageBox.Show(ex.Message, "error", MessageBoxButtons.OK, MessageBoxIcon.Error)
        End Try
    End Sub
End Class

0 个答案:

没有答案