[英]C# WPF DataGrid (ItemsSource = Database Table) - additional column: How to keep changes when (re-)sorting the DataGrid?
這里有一個棘手的問題:我有一個由訪問表填充的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);
現在,我當然可以將所有檢查存儲在bool數組中或其他任何東西中,但是是否有一個聰明的解決方案來在對DataGrid排序時保持檢查設置?
親切的問候!
我想我已經提出了一個好的解決方案:
填充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(...)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.