The .Net data model implies that a control bound to a database using
DbDataAdapter and
DataTable objects does not immediately post changes after they have been made. Instead, changes are accumulated in the
DataTable and you have to manually call a specific method to update the database. The XtraGrid behaves in a similar way: changes you made while editing data (adding, deleting or modifying records) are saved in a corresponding
DataTable. To post these changes to the database, you should call the data adapter's
System.Data.Common.DbDataAdapter.Update method.
Before calling this method, make sure that the grid control has saved all the changes made to the currently focused row (the end-user could enter new data but forget to update the row). For this purpose, you need to call the BaseView.PostEditor and ColumnView.UpdateCurrentRow methods.
The following code lists the
UpdateDatasource method which posts the changes stored in the custom
Suppliers and
ProductsDataTables to a database. It is assumed that the data adapters (
oleDbDataAdapter1 and
oleDbDataAdapter2) contain appropriate Update SQL statements to modify the corresponding tables in the database. By default, these statements are created by the adapter's Wizards.
The dataSet11 object represents a DataSet instance and this provides access to our tables.
C#
Copy Code
using DevExpress.XtraGrid;
using DevExpress.XtraGrid.Views.Base;
using System.Data.Common;
//...
public void UpdateDatasource(GridControl grid) {
//Save the latest changes to the bound DataTable
ColumnView View = (ColumnView)grid.FocusedView;
if (!(view.PostEditor() && View.UpdateCurrentRow())) return;
//Update the database's Suppliers table to which oleDBDataAdapter1 is connected
DoUpdate(oleDbDataAdapter1, dataSet11.Tables["Suppliers"]);
//Update the database's Products table to which the oleDbDataAdapter2 is connected
DoUpdate(oleDbDataAdapter2, dataSet11.Tables["Products"]);
}
public void DoUpdate(DbDataAdapter dataAdapter, System.Data.DataTable dataTable) {
try {
dataAdapter.Update(dataTable);
} catch(Exception ex) {
MessageBox.Show(ex.Message);
}
}
Visual Basic
Copy Code
Imports DevExpress.XtraGrid
Imports DevExpress.XtraGrid.Views.Base
Imports System.Data.Common
'...
Public Sub UpdateDatasource(ByVal grid As GridControl)
'Save the latest changes to the bound DataTable
Dim View As ColumnView = grid.FocusedView
If Not (view.PostEditor() And View.UpdateCurrentRow()) Then Return
'Update the database's Suppliers table to which oleDBDataAdapter1 is connected
DoUpdateTable(oleDbDataAdapter1, dataSet11.Tables("Suppliers"))
'Update the database's Products table to which the oleDbDataAdapter2 is connected
DoUpdateTable(oleDbDataAdapter2, dataSet11.Tables("Products"))
End Sub
Public Sub DoUpdateTable(ByVal dataAdapter As DbDataAdapter, ByVal dataTable As System.Data.DataTable)
Try
dataAdapter.Update(dataTable)
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
End Sub