要用到两个事件,CellMouseClick和Sorted事件,C#代码如下:
List<object[]> lastRow = new List<object[]>(); int colindex = 0; private void dgv_CellMouseClick(object sender, DataGridViewCellMouseEventArgs e) { if (e.RowIndex >= 0 || dgv.Rows.Count == 0) return; if (lastRow.Count == 0) { colindex = e.ColumnIndex; int index = dgv.Rows.Count - 1; lastRow.Add(((DataTable)dgv.DataSource).Rows[index].ItemArray); dgv.Rows.Remove(dgv.Rows[dgv.Rows.Count - 1]); } } private void dgv_Sorted(object sender, EventArgs e) { if (lastRow.Count == 0) return; DataTable dt=((DataTable)dgv.DataSource); DataView dv = dt.DefaultView;
dv.Sort = dt.Columns[colindex].ColumnName; //默认排序为升序,可以自己设定 dt = dv.ToTable (); dt.Rows.Add(lastRow[0]); lastRow.Clear(); dgv.DataSource = dt; }