swap rows in datagridview in c#

namco picture namco · Apr 15, 2011 · Viewed 9.6k times · Source


i have a datagridview which is not related with dataTable.
and i want to swap for example 1st and 10th rows in datagridview.
i use this code for it

int row_1 = 1;
int row_10 = 10;
for(int i=0;i<grid.ColumnCount;i++)
{
  string temp = grid.Rows[row_1].Cells[i].Value.ToString();
  grid.Rows[row_1].Cells[i].Value = grid.Rows[row_10].Cells[i].Value.ToString();
  grid.Rows[row_10].Cells[i].Value = temp;
}

but i want to know is there any simple way to do this??

Answer

DarkSquirrel42 picture DarkSquirrel42 · Apr 15, 2011
var r10 = grid.Rows[9];
var r1 = grid.Rows[0];
grid.Rows.Remove(r1);
grid.Rows.Remove(r10);
grid.Rows.Insert(0, r10);
grid.Rows.Insert(9, r1);