我在 Win Forms 应用程序中有一个数据绑定(bind) DataGridView,用户可能已按列排序。问题是这样的:用户在编辑排序列中的单元格后离开一行后,该行立即重新排序。
这会让用户迷失方向,并且无法一起编辑行组。
我正在寻找的解决方案将在初始排序后有效地禁用自动重新排序,然后仅在用户请求时再次排序。
最佳答案
为了其他人的利益,这是我想出的解决方案,但我希望听到更好的解决方案。
我向名为 SORT_ORDER 的 DataTable 添加了一个额外的非持久列,它仅用于排序。
当用户单击要排序的列时,我将值和值类型从所选列复制到 SORT_ORDER 列,然后按 SORT_ORDER 进行排序。由于 SORT_ORDER 不可见且无法编辑,因此即使用户编辑所选列,排序顺序也不会更改。事件处理程序如下所示:
private void MyDataGridView_ColumnHeaderMouseClick(object sender, DataGridViewCellMouseEventArgs e) {
dirtyCellListenerEnabled = false;
SORT_ORDER.ValueType = MyDataGridView.Columns[e.ColumnIndex].ValueType;
foreach(DataGridViewRow r in MyDataGridView.Rows) {
r.Cells[SORT_ORDER.Index].Value = r.Cells[e.ColumnIndex].Value;
}
switch(MyDataGridView.SortOrder) {
case System.Windows.Forms.SortOrder.None:
MyDataGridView.Sort(SORT_ORDER, ListSortDirection.Ascending);
break;
case System.Windows.Forms.SortOrder.Ascending:
MyDataGridView.Sort(SORT_ORDER, ListSortDirection.Descending);
break;
case System.Windows.Forms.SortOrder.Descending:
MyDataGridView.Sort(SORT_ORDER, ListSortDirection.Ascending);
break;
}
dirtyCellListenerEnabled = true;
}
请注意,我必须禁用并重新启用我的单元监听器,这样我的代码才不会将排序列更新视为真正的更改。
在找到这个解决方案之前,我也曾尝试将排序列添加到 DataGridView,但它不起作用,因为 DataGridView 无法对其数据源中不存在的列进行排序。
我确信我还可以做一些其他调整,例如在填充 SORT_ORDER 时暂停更新并在所选列上显示排序字形。
关于c# - 防止数据绑定(bind) DataGridView 在编辑时进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8073710/