namco
namco

Reputation: 6338

swap rows in datagridview in c#


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

Upvotes: 7

Views: 11967

Answers (6)

Georg
Georg

Reputation: 2096

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);
  }
}

Upvotes: 0

MintyAnt
MintyAnt

Reputation: 3058

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!

Upvotes: 4

AGuyCalledGerald
AGuyCalledGerald

Reputation: 8150

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())

Upvotes: 1

DarkSquirrel42
DarkSquirrel42

Reputation: 10257

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);

Upvotes: 10

Seth Moore
Seth Moore

Reputation: 3545

Try:

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

Upvotes: 2

Gabriel
Gabriel

Reputation: 1443

HI,
Have you tried:

DataGridViewRow temp =grid.Rows[row_1];
grid.Rows[row_1] = grid.Rows[row_10];
grid.Rows[row_10] = temp;

Upvotes: 4

Related Questions