Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I Get a WPF DataGrid to Save Changes Back to the DataBase?

How do I get a WPF DataGrid to save changes back to the database?

I've data-bound my DataGrid control to a DataTable object, and populated that table with a very simple SELECT query that retrieves some basic information. The data shows up just fine in the control.

But when I use the control to edit the data, the changes are not pushed back to the DB.

Does anyone know what I'm missing?

like image 434
Giffyguy Avatar asked Jul 21 '09 00:07

Giffyguy


People also ask

How do you refresh a data grid?

Use the dataGrid. refresh method. Use the reload() method of your DataGrid's dataSource as shown in the following help topic: cacheEnabled. Create a new instance of a store and assign it to your DataGrid's dataSource.

Can user add rows DataGrid WPF?

WPF DataGrid (SfDataGrid) provides built-in row called AddNewRow. It allows user to add a new row to underlying collection. You can enable or disable by setting SfDataGrid.

What is Datagridview in WPF?

The DataGrid control enables you to display and edit data from many different sources, such as from a SQL database, LINQ query, or any other bindable data source. For more information, see Binding Sources Overview.


1 Answers

Performing Updates

When the user edits the Customers data within the DataGrid, the bound in-memory DataTable is updated accordingly. However, these updates are not automatically written back to the database. It is up to the developer to decide when changes to the DataTable are written back to the database depending on the requirements of the application. For example, in some cases, you might wish to submit a batch of changes via a "Submit" button, or you may wish to have the database updated as the user commits each row edit. In order to support these, the rows that the DataTable contains have a RowState property which indicates whether they contain changes which should be synchronized with the database. The synchronization process is easily achieved via the TableAdapter's Update method. url: WPF DataGrid examples

The following example shows how the RowChanged and RowDeleted events can be handled so that changes in the DataTable state are written to the database each time the user changes a row:

public CustomerDataProvider()
{
    NorthwindDataSet dataset = new NorthwindDataSet();

    adapter = new CustomersTableAdapter();
    adapter.Fill(dataset.Customers);

    dataset.Customers.CustomersRowChanged +=
        new NorthwindDataSet.CustomersRowChangeEventHandler(CustomersRowModified);
    dataset.Customers.CustomersRowDeleted +=
        new NorthwindDataSet.CustomersRowChangeEventHandler(CustomersRowModified);
}

void CustomersRowModified(object sender, NorthwindDataSet.CustomersRowChangeEvent e)
{
    adapter.Update(dataset.Customers);
}
like image 99
Vincent De Smet Avatar answered Oct 11 '22 14:10

Vincent De Smet