编辑时防止数据绑定DataGridView排序

did*_*dge 4 c# sorting datagridview edit winforms

我在Win Forms应用程序中有一个数据绑定DataGridView,用户可能已按列排序.问题是这样的:在用户在排序列中编辑单元格后离开行之后,该行立即被重新排序.

这对于用户来说非常迷惑,并且使得编辑行组成不可能.

我正在寻找的解决方案将在初始排序后有效地禁用自动重新排序,然后仅在用户请求时再次排序.

did*_*dge 7

为了别人的利益,这是我提出的解决方案,但我很想听到更好的解决方案.

我在DataTable中添加了一个名为SORT_ORDER的附加非持久列,该列仅用于排序.

当用户单击要排序的列时,我将值和值类型从选定列复制到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;
    }
Run Code Online (Sandbox Code Playgroud)

请注意,我必须禁用并重新启用我的单元格侦听器,以便我的代码不会将排序列更新视为真正的更改.

在到达此解决方案之前,我还尝试将排序列添加到DataGridView,但它不起作用,因为DataGridView无法对其数据源中不存在的列进行排序.

我确信我还可以做一些其他的调整,例如在填充SORT_ORDER并在所选列上显示排序字形时暂停更新.

  • 由于没有人提供更好的解决方案,我会接受我自己的答案. (2认同)