2011-04-15 56 views
7


tengo un datagridview que no está relacionado con dataTable.
y quiero intercambiar, por ejemplo, las filas 1ª y 10ª en datagridview.
utilizo este código para ellointercambiar filas en datagridview en 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; 
} 

pero yo quiero saber ¿hay alguna manera simple de hacer esto ??

Respuesta

4

HI,
¿Usted ha intentado:

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

recibo el mensaje: DataGridViewRowCollection.this [INT] no puede ser asignado - es de solo lectura – Georg

2

Probar:

DataGridViewRow temp = grid.Rows[row_1].Clone(); 
grid.Rows[row_1] = grid.Rows[row_10].Clone(); 
grid.Rows[row_10] = temp; 
8
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); 
1

Así como además:

si es necesario intercambiar más a menudo, ponen el método anterior usted prefiere más en su propia clase y llama al método (por ejemplo, Interchange())

4

Quiero comentar sobre esto.

Si bien -may- han sido posible hacer un intercambio recta en C# antes, como Smoore/Gabriels-

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

esto ya no es posible, ya que grid.Rows [índice] es de sólo lectura.

En su lugar, utilice el método DarkSquirrels para guardar las dos filas, eliminar las filas y volverlas a insertar intercambiadas.

Si alguien conoce un método mejor (ya que esto es como un método de 6 líneas por iteslf sin la lógica para encontrar el otro valor) ¡por favor comente!

0

Este método funciona bien:

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