C# WPF DataGrid (ItemsSource = Database Table) - additional column: How to keep changes when (re-)sorting the DataGrid?

StackOverflow https://stackoverflow.com/questions/16622792

  •  29-05-2022
  •  | 
  •  

Question

got a tricky question here: I have a DataGrid that's being filled (DataGrid.ItemsSource) by an Access Table.

What's best practice to show additional columns for the user and keep changes in this column upon (re-)sorting?

In my case the additional column is a CheckBoxColumn for the user, to select those lines in the DataGrid he wants to edit. The checks disappear if you sort the DataGrid.

Code:

using (OleDbConnection connection = new OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + AppDomain.CurrentDomain.BaseDirectory + "Test.accdb"))
{
    string strDbCmd = "SELECT * FROM Table1";
    OleDbDataAdapter daOleDb = new OleDbDataAdapter(strDbCmd, connection);
    DataTable dtResult = new DataTable(); // this is actually a global
    daOleDb.FillSchema(dtResult, SchemaType.Source);
    daOleDb.Fill(dtResult);
    DataGrid1.ItemsSource = dtResult.DefaultView;
    DataGridCheckBoxColumn dgCol = new DataGridCheckBoxColumn();
    DataGrid1.Columns.Insert(0, dgCol);
}

I cannot alter dtResult (which is actually a global) as I later on will use that to update the database:

// Later on somewhere else:
OleDbDataAdapter daOleDb = new OleDbDataAdapter(strDbCmd, connection);
// [...]
daOleDb.Update(dtResult);

Now of course I could store all checks in a bool array or anything, but is there a clever solution to keep checks set upon sorting the DataGrid?

Kinds regards!

Was it helpful?

Solution

I guess I've come up with a good solution:

After filling the DataTable, you add a bool column manually:

// [...]
daOleDb.Fill(dtResult);
DataColumn dtCol = new DataColumn("Bool", typeof(Boolean));
dtCol.DefaultValue = false;
dtResult.Columns.Add(dtCol);
dtCol.SetOrdinal(0);
DataGrid1.ItemsSource = dtResult.DefaultView;

This will not affect the "RowsChanged" event and as it's an added column, before doing

daOleDb.Update(dtResult);

you can simply delete/remove it again (shouldn't make any difference as added columns do not affect any ChangesEvent when being deleted either)

dtResult.Columns[0].Remove(); // or Columns.Delete(...)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top