Summary: Disable sorting after clicking DataGridView columnheader,Prevent databound DataGridView from sorting while editing!
Problem:I have a databound DataGridView in a WinForms which the user may have sorted by a column. The problem is this: after the user leaves a row after editing a cell in the sorted column, the row is immediately re-sorted.This is very disorienting for users and makes editing groups of rows together impossible.
Solution: re-databound when user start editing, run program, or sorted finish, to do that can disable automatic re-sorting.ting after an initial sort and then only sort again when the user requests it.
/// <summary> /// 控件状态 When the Program start or stop, we can re-databound dgv to disable re-sorting /// </summary> public void ChangeStatus(bool status) { Invoke((ThreadStart)delegate() { mydgv.Columns["status"].SortMode = status ? DataGridViewColumnSortMode.Automatic : DataGridViewColumnSortMode.NotSortable;//排序功能状态更改 if (status) { mydgv.Sort(mydgv.Columns["status"], ListSortDirection.Ascending); //停止运行任务,自动排序 } else { DataGridViewRebindsource(mydgv); //开始运行任务,排序完后重新绑定数据 } }); } /// <summary> /// 列头单击排序事件——after ColumnHeaderMouseClick to re-databound dgv to disable re-sorting /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void mydgv_ColumnHeaderMouseClick(object sender, DataGridViewCellMouseEventArgs e) { switch (mydgv.SortOrder) { case System.Windows.Forms.SortOrder.None: mydgv.Sort(mydgv.Columns[e.ColumnIndex], ListSortDirection.Ascending); break; case System.Windows.Forms.SortOrder.Ascending: mydgv.Sort(mydgv.Columns[e.ColumnIndex], ListSortDirection.Descending); break; case System.Windows.Forms.SortOrder.Descending: mydgv.Sort(mydgv.Columns[e.ColumnIndex], ListSortDirection.Ascending); break; } DataGridViewRebindsource(mydgv); //排序完后重新绑定数据 } /// <summary> /// 重新绑定dgv数据 清除自动排序 —— function: re-databound dgv to disable re-sorting /// </summary> /// <param name="dgv"></param> public void DataGridViewRebindsource(DataGridView dgv) { DataTable table = new DataTable(); int dgvColumnsNum = dgv.Columns.Count; int dgvRowsNum = dgv.Rows.Count; //获取datagridview的列 foreach (DataGridViewColumn dgvc in dgv.Columns) { if (dgvc.Visible && dgvc.CellType != typeof(DataGridViewCheckBoxCell)) { DataColumn dc = new DataColumn(); dc.ColumnName = dgvc.DataPropertyName; table.Columns.Add(dc); } } //获取datagridview的行 for (int i = 0; i < dgvRowsNum; i++) { DataRow dataRow = table.NewRow(); int j = 0; for (j = 0; j < dgvColumnsNum; j++) { dataRow[j] = dgv.Rows[i].Cells[j].Value; } table.Rows.Add(dataRow); } dgv.DataSource = table; }