For me this worked:
public static void MoveUp(DataGridView dgv)
{
if (dgv.RowCount <= 0)
return;
if (dgv.SelectedRows.Count <= 0)
return;
var index = dgv.SelectedCells[0].OwningRow.Index;
if (index == 0)
return;
var rows = dgv.Rows;
var prevRow = rows[index - 1];
rows.Remove(prevRow);
prevRow.Frozen = false;
rows.Insert(index, prevRow);
dgv.ClearSelection();
dgv.Rows[index - 1].Selected = true;
}
public static void MoveDown(DataGridView dgv)
{
if (dgv.RowCount <= 0)
return;
if (dgv.SelectedRows.Count <= 0)
return;
var rowCount = dgv.Rows.Count;
var index = dgv.SelectedCells[0].OwningRow.Index;
if (index == rowCount - 1) // Here used 1 instead of 2
return;
var rows = dgv.Rows;
var nextRow = rows[index + 1];
rows.Remove(nextRow);
nextRow.Frozen = false;
rows.Insert(index, nextRow);
dgv.ClearSelection();
dgv.Rows[index + 1].Selected = true;
}
The difference to Mario's code is that I used (rowCount - 1) instead of (rowCount - 2) ... After changing this, it worked perfectly. Before the move-down didn't work if you only have 2 rows in your DataGridView...