Skip to content

Commit

Permalink
add move up/down function
Browse files Browse the repository at this point in the history
  • Loading branch information
twilightty committed May 20, 2024
1 parent 13e57f2 commit 9363ec1
Show file tree
Hide file tree
Showing 2 changed files with 65 additions and 0 deletions.
26 changes: 26 additions & 0 deletions Form1.Designer.cs

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

39 changes: 39 additions & 0 deletions Form1.cs
Original file line number Diff line number Diff line change
Expand Up @@ -299,5 +299,44 @@ private void label1_Click(object sender, EventArgs e)
{

}

private void button7_Click(object sender, EventArgs e)
{
MoveSelectedRow(-1); //Moveup
}

private void MoveSelectedRow(int direction)
{
// Exit if no cell is selected or multiple cells are selected
if (dataGridView1.SelectedCells.Count != 1)
{
MessageBox.Show("Please select a single cell to move its row.");
return;
}

// Get the selected cell
DataGridViewCell selectedCell = dataGridView1.SelectedCells[0];
int rowIndex = selectedCell.RowIndex;
int newRowIndex = rowIndex + direction;

// Exit if the new row index is out of bounds
if (newRowIndex < 0 || newRowIndex >= dataGridView1.Rows.Count)
{
return;
}

// Swap the rows
DataGridViewRow selectedRow = dataGridView1.Rows[rowIndex];
dataGridView1.Rows.Remove(selectedRow);
dataGridView1.Rows.Insert(newRowIndex, selectedRow);

// Reselect the moved cell
dataGridView1.ClearSelection();
dataGridView1.Rows[newRowIndex].Cells[selectedCell.ColumnIndex].Selected = true;
}
private void button8_Click(object sender, EventArgs e)
{
MoveSelectedRow(1); //Move down
}
}
}

0 comments on commit 9363ec1

Please sign in to comment.