【问题标题】:C# WPF DataGrid (ItemsSource = Database Table) - additional column: How to keep changes when (re-)sorting the DataGrid?C# WPF DataGrid (ItemsSource = Database Table) - 附加列:如何在(重新)排序 DataGrid 时保持更改?
【发布时间】:2013-05-13 10:24:07
【问题描述】:

这里有一个棘手的问题: 我有一个由访问表填充的 DataGrid (DataGrid.ItemsSource)。

为用户显示其他列并在(重新)排序时保留此列中的更改的最佳做法是什么?

在我的情况下,附加列是用户的 CheckBoxColumn,用于选择他想要编辑的 DataGrid 中的那些行。如果您对 DataGrid 进行排序,检查就会消失。

代码:

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);
}

我无法更改 dtResult(它实际上是一个全局的),因为我稍后将使用它来更新数据库:

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

现在我当然可以将所有检查存储在一个布尔数组或任何东西中,但是有没有一个聪明的解决方案可以在对 DataGrid 排序时保持检查设置?

问候!

【问题讨论】:

    标签: c# wpf datagrid itemssource


    【解决方案1】:

    我想我想出了一个很好的解决方案:

    填写完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;
    

    这不会影响“RowsChanged”事件,因为它是一个添加的列,在做之前

    daOleDb.Update(dtResult);
    

    您可以简单地再次删除/删除它(应该没有任何区别,因为添加的列在被删除时也不会影响任何 ChangesEvent)

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

    【讨论】:

      猜你喜欢
      • 2012-06-22
      • 2010-11-09
      • 1970-01-01
      • 2013-04-25
      • 2010-12-15
      • 1970-01-01
      • 2012-05-01
      • 2011-04-22
      • 2010-11-17
      相关资源
      最近更新 更多