swap rows in datagridview in c#
Asked Answered
I

6

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

Indebted answered 15/4, 2011 at 11:39 Comment(1)
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.Danielledaniels
P
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);
Philae answered 15/4, 2011 at 12:0 Comment(0)
E
4

HI,
Have you tried:

DataGridViewRow temp =grid.Rows[row_1];
grid.Rows[row_1] = grid.Rows[row_10];
grid.Rows[row_10] = temp;
Explosive answered 15/4, 2011 at 11:46 Comment(1)
I get the message: DataGridViewRowCollection.this[int] cannot be assigned -- it is read onlyTierza
P
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!

Painkiller answered 16/12, 2011 at 0:37 Comment(0)
S
2

Try:

DataGridViewRow temp = grid.Rows[row_1].Clone();
grid.Rows[row_1] = grid.Rows[row_10].Clone();
grid.Rows[row_10] = temp;
Sink answered 15/4, 2011 at 11:49 Comment(0)
D
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())

Dwanadwane answered 15/4, 2011 at 12:13 Comment(0)
T
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);
  }
}
Tierza answered 22/2, 2016 at 9:27 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.