大家好我需要帮助更新datagridview上的数据。方案是当我单击“搜索”按钮时,它将查询相应的数据并显示我想要的数据网格视图。然后我想更新,如果他们的任何更改或从datagridview删除的数据,然后每当我点击更新按钮时,也更新到我的mysql表的新数据或记录。问题是,当我点击我的搜索按钮时,消息框出现"该表不包含任何要保存的更改。"这意味着没有变化,但我已经在datagridview中更改了值。有人可以帮帮我吗? 这是我的搜索按钮代码:
Public Class Form1
Dim con As New MySqlConnection
Dim result As Integer
Dim cmd As New MySqlCommand
Dim da As New MySqlDataAdapter
Dim ds As New DataSet
Dim dr As MySqlDataReader
Dim sql As String
Dim dt As New DataTable
Private Sub cmdSearch_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdSearch.Click
Dim conn As New MySqlConnection
conn.ConnectionString = ("server=127.0.0.1;user id=root;password=12345;database=dbsis3bkenth;")
Try
conn.Open()
sql = "SELECT LName,FName,MI FROM tblsisterbrother where IDNoBrodSis = '" & cbIDNo.Text & "'"
cmd = New MySqlCommand(sql, conn)
dr = cmd.ExecuteReader
dr.Read()
If dr.HasRows = True Then
MessageBox.Show("Record Found.!")
Else
MessageBox.Show("Record Unfound.!")
End If
dr.Close()
Catch ex As MySqlException
MessageBox.Show("Error in searching to database:error is:" & ex.Message)
Exit Sub
End Try
dr.Close()
RemoveHandler DataGridView1.CellValidating, AddressOf DataGridView1_CellValidating
da.SelectCommand = cmd
da.Fill(ds, "tblsisterbrother")
DataGridView1.DataSource = ds.Tables(0)
conn.Dispose()
conn.Close()
End Sub
以下是我的更新按钮的代码:
Private Sub cmdUpdate_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdUpdate.Click
DataGridView1.EndEdit()
Dim dt As DataTable
dt = TryCast(DataGridView1.DataSource, DataTable)
If dt.GetChanges() Is Nothing Then
MessageBox.Show("The table contains no changes to save.")
Else
Dim builder = New MySqlCommandBuilder(da)
Dim rowsAffected As Integer = da.Update(dt)
If rowsAffected = 0 Then
MessageBox.Show("No rows were affected by the save operation.")
Else
MessageBox.Show(rowsAffected & " rows were affected by the save operation.")
End If
End If
End Sub
结束班
请帮助我们解决我的问题:)
答案 0 :(得分:0)
获取DataTable的副本,该副本包含自加载或上次调用AcceptChanges以来对其所做的所有更改。
由于您声明了DataTable并且只加载了一次,因此它按预期工作。
要使它像你想要的那样工作,你必须使用CellEditEnd事件,并从DataGrid.DataSource调用GetChanges()方法,如下所示:
Private Sub DataGridView1_CellEndEdit(sender As Object, e As DataGridViewCellEventArgs) Handles DataGridView1.CellEndEdit
Dim Changes As DataTable
Changes = TryCast(DataGridView1.DataSource, DataTable).GetChanges()
End Sub