fernando.reyes fernando.reyes - 24 days ago 11
C# Question

Update database linked to DataGrid dynamically

I want to put several buttons on my WPF form and update dynamically my DataGrid with the data from a different database for each button, let say, I have 3 databases and 3 buttons, and when you push one button you get the data from 1 different database.

But I want the data on the DataGrid to update back into the database when a change is made on the Grid, so I don't have to program all the "save" stuff.

Right now, the code that I have is this:

try
{
OleDbConnection conn = new OleDbConnection(
"Provider=Microsoft.Jet.OLEDB.4.0; " +
"Data Source=MaterialDB.mdb");
OleDbDataAdapter adapter = new OleDbDataAdapter("SELECT * FROM myTable", conn);

myDataSet = new DataSet();
adapter.Fill(myDataSet, "myTable");

var be = CatalogsGrid.GetBindingExpression(DataGrid.ItemsSourceProperty);

CatalogsGrid.DataContext = myDataSet;
CatalogsGrid.ItemsSource = myDataSet.Tables[0].DefaultView;
Binding nbe = new Binding();
nbe.Source = myDataSet;
nbe.Mode = BindingMode.TwoWay;
nbe.UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged;
nbe.Path = new PropertyPath("myTable");
nbe.BindsDirectlyToSource = true;
CatalogsGrid.SetBinding(DataGrid.ItemsSourceProperty, nbe);


CatalogsGrid.Items.Refresh();

}


This code loads the data from a database into the grid, but I edit the data and it doesn't update back into the MS Access table.

Oh, it is still not coded but the "myTable" should be a string where I put the name of the different tables I want to show and update from the grid.

What am I missing?

Answer

The DataGrid does not save changes automatically, that's up to you (your application) to decide, but it writes back changes to the underlying DataTable.

So as I understand, you want to avoid having a save button and save changes back to the database immediately after they have changed. What you need now is to know when something has changed, and your DataSet can help you with that:

myDataSet = new DataSet();
myDataTable = myDataSet.Tables["myTable"];
adapter.Fill(myDataTable);

// Update the DB whenever a row changes
myDataTable.OnRowChanged += (s, e) =>
{
    adapter.Update(myDataTable);
}
Comments