swap rows in datagridview in c#
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??
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);
HI,
Have you tried:
DataGridViewRow temp =grid.Rows[row_1];
grid.Rows[row_1] = grid.Rows[row_10];
grid.Rows[row_10] = temp;
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!
Try:
DataGridViewRow temp = grid.Rows[row_1].Clone();
grid.Rows[row_1] = grid.Rows[row_10].Clone();
grid.Rows[row_10] = temp;
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())
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);
}
}
精彩评论