7


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??

namco
  • 6,208
  • 20
  • 59
  • 83
  • This is not good, you don't need to call `Value.ToString()` and so on, just store the Value in an object. That will be generic, unlike your code, which only works with strings. – Zoli Jun 07 '21 at 15:37

6 Answers6

10
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);
DarkSquirrel42
  • 10,167
  • 3
  • 20
  • 31
4

HI,
Have you tried:

DataGridViewRow temp =grid.Rows[row_1];
grid.Rows[row_1] = grid.Rows[row_10];
grid.Rows[row_10] = temp;
Gabriel
  • 1,435
  • 3
  • 17
  • 24
  • I get the message: DataGridViewRowCollection.this[int] cannot be assigned -- it is read only – Georg Feb 22 '16 at 08:38
4

I wanted to comment on this.

While it -may- have been possible to do a straight swap in C# before, like smoore/Gabriels-

DataGridViewRow temp = grid.Rows[row_1].Clone();
grid.Rows[row_1] = grid.Rows[row_10].Clone();
grid.Rows[row_10] = temp;

This is no longer possible, as grid.Rows[index] is read only.

Instead, use DarkSquirrels method of saving the two rows, removing the rows, and re-inserting them swapped.

If somebody knows a better method (as this is like a 6 line method by iteslf without the logic to find the other value) please do comment!

MintyAnt
  • 2,978
  • 7
  • 25
  • 37
2

Try:

DataGridViewRow temp = grid.Rows[row_1].Clone();
grid.Rows[row_1] = grid.Rows[row_10].Clone();
grid.Rows[row_10] = temp;
Seth Moore
  • 3,575
  • 2
  • 23
  • 33
1

Just as addition:

if you need interchange more often, put the method above you prefer most in its own class and call the method (e.g. Interchange())

AGuyCalledGerald
  • 7,882
  • 17
  • 73
  • 120
0

This method works fine:

private static void SwapRows(DataGridView grid, int row1, int row2)
{
  if (row1 != row2 && row1 >= 0 && row2 >= 0 && row1 < grid.RowCount && row2 < grid.RowCount)  
  {
    var rows = grid.Rows.Cast<DataGridViewRow>().ToArray();
    var temp = rows[row1];
    rows[row1] = rows[row2];
    rows[row2] = temp;
    grid.Rows.Clear();
    grid.Rows.AddRange(rows);
  }
}
Georg
  • 1,946
  • 26
  • 18