简体   繁体   English

C#WPF DataGrid(ItemsSource =数据库表)-附加列:如何在(重新)排序DataGrid时保留更改?

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

got a tricky question here: I have a DataGrid that's being filled (DataGrid.ItemsSource) by an Access Table. 这里有一个棘手的问题:我有一个由访问表填充的DataGrid(DataGrid.ItemsSource)。

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. 在我的情况下,附加列是用户的CheckBoxColumn,以便在他想要编辑的DataGrid中选择那些行。 The checks disappear if you sort the DataGrid. 如果对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: 我无法更改dtResult(实际上是全局的),因为稍后我将使用它来更新数据库:

// 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? 现在,我当然可以将所有检查存储在bool数组中或其他任何东西中,但是是否有一个聪明的解决方案来在对DataGrid排序时保持检查设置?

Kinds regards! 亲切的问候!

I guess I've come up with a good solution: 我想我已经提出了一个好的解决方案:

After filling the DataTable, you add a bool column manually: 填充DataTable之后,您可以手动添加bool列:

// [...]
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 在执行此操作之前,这不会影响“ RowsChanged”事件,因为它是添加的列

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) 您只需再次删除/删除它(就不会有任何区别,因为添加的列在删除时也不会影响任何ChangesEvent)

dtResult.Columns[0].Remove(); // or Columns.Delete(...)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM