DataGridView点击排序完成后如何禁止自动排序

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 = ; i < dgvRowsNum; i++)
{
DataRow dataRow = table.NewRow();
int j = ;
for (j = ; j < dgvColumnsNum; j++)
{
dataRow[j] = dgv.Rows[i].Cells[j].Value;
}
table.Rows.Add(dataRow);
}
dgv.DataSource = table;
}
上一篇:在使用element-ui搭建的表格中,实现点击"定位"按钮后,屏幕滚动到对应行的位置


下一篇:宝塔控制面板创建ftp后链接不上的解决方法