Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

DataGridView - switch rows

Status
Not open for further replies.

tzzdvd

Programmer
Aug 17, 2001
52
IT
Hi to all.
I would like to switch two rows in a datagridview without clearing the datagrid.
It is easy to make such a code:
Code:
dgv.Clear();
for (int x = 0; x < n; x++)
{
   dgv.Rows.Add(...);  // in another order
}
but I don't want the
Code:
dgv.Clear()
line of code.
The most beautiful thing should be drag and drop an entire row to another position but I don't know how and I haven't any idea too.
For me, it is enough to add 2 buttons in the row to put up or down the row for only one row.
But I don't know how to switch two rows and if it is possible.

Thanks' for all

Davide
 
Here is a possible solution I have found:
Code:
private void dgvCB_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
   switch(e.ColumnIndex)
   {
       case 0:  // column of up button
           if (e.RowIndex > 0)
           {
               dgv.Rows.InsertCopy(e.RowIndex, e.RowIndex - 1);
               for (int x = 0; x < dgv.Columns.Count; x++)
                   dgv.Rows[e.RowIndex - 1].Cells[x].Value = dgv.Rows[e.RowIndex + 1].Cells[x].Value;
               dgv.Rows.RemoveAt(e.RowIndex + 1);
               dgv.Rows[e.RowIndex - 1].Selected = true;
           }
           break;
       case 1:  // column of down button
           if (e.RowIndex < dgv.Rows.Count -1)
           {
               dgv.Rows.InsertCopy(e.RowIndex, e.RowIndex + 2);
               for (int x = 0; x < dgv.Columns.Count; x++)
                   dgv.Rows[e.RowIndex + 2].Cells[x].Value = dgv.Rows[e.RowIndex].Cells[x].Value;
               dgv.Rows.RemoveAt(e.RowIndex);
               dgv.Rows[e.RowIndex + 1].Selected = true;
           }
           break;
    }
}
It functions but I don't like very much: what happens if during this change a new row is added or removed?
Do you think that this is a problem?
If so, a
Code:
lock(dgv)
{
...code
}
can be useful?

Davide
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top