Domanda

My problem is that when I am editing cells in the datagrid the database is not updating. The code I used is below.

Public Class Form9
    Inherits System.Windows.Forms.Form
    Dim sql As String = "SELECT * FROM User_Account WHERE IsAdmin=False"
    Dim conn As New OleDb.OleDbConnection
    Dim sqlCom As New System.Data.OleDb.OleDbCommand(sql, conn)
    Dim da As New OleDb.OleDbDataAdapter(sqlCom)
    Dim dt As New DataTable

    Private Sub Form9_Load(ByVal sender As Object, ByVal e As EventArgs) _
        Handles MyBase.Load

        conn.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source='" & _
            folderpath & "\TKIC\TKIC_Data_Storage.accdb'" & _
            ";Persist Security Info=True"
        conn.Open()
        da.Fill(dt)
        DataGridView1.DataSource = dt
    End Sub

    Private Sub Button2_Click(ByVal sender As Object, ByVal e As EventArgs)
        DataGridView1.Update()
        dt.AcceptChanges()
    End Sub
End Class
È stato utile?

Soluzione

You have to update the underlying DataTable. The DataGridView.Update causes the control to redraw the invalidated regions within its client area (basically repaints). The dt.AcceptChanges() only commits the changes in the DataTable not the database. The database has to be updated explicitly using the adapter and appropriate command texts. The OleDbCommandBuilder helps in forming the appropriate command texts.

Use the OleDbDataAdapter to update the database.

OleDbCommandBuilder cb = new OleDbCommandBuilder(adapter);
cb.QuotePrefix = "[";
cb.QuoteSuffix = "]";
adapter.Update(datatable);
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top