在datagridview里面,怎样实现整行的上移和下移呢?

代码如下:

private void button1_Click(object sender, EventArgs e)
{
  List<string> list = new List<string>();
  List<string> list1 = new List<string>();

  int rowIndex = dataGridView1.CurrentCell.RowIndex;

  int row = dataGridView1.CurrentCell.RowIndex + 1;
  int col = dataGridView1.CurrentCell.ColumnIndex + 1;

  if (1 == row)
  {
    MessageBox.Show("已是第一行,无法上移");
    return;
  }

  int count = dataGridView1.ColumnCount;
  for (int i = 0; i < count; i++)
  {
    list.Add(dataGridView1.Rows[row - 1].Cells[col - 1 + i].Value.ToString());
    list1.Add(dataGridView1.Rows[row - 2].Cells[col - 1 + i].Value.ToString());
  }

  for (int j = 0; j < count; j++)
  {

    dataGridView1.Rows[row - 1].Cells[col - 1 + j].Value = list1.ElementAt(j);
    dataGridView1.Rows[row - 2].Cells[col - 1 + j].Value = list.ElementAt(j);
  }

  dataGridView1.Rows[rowIndex - 1].Cells[0].Selected = true;
  dataGridView1.Rows[rowIndex].Cells[0].Selected = false;

  dataGridView1.CurrentCell = dataGridView1.Rows[rowIndex - 1].Cells[0];

}

 

private void button2_Click(object sender, EventArgs e)
{

  List<string> list = new List<string>();
  List<string> list1 = new List<string>();

  int rowIndex = dataGridView1.CurrentCell.RowIndex;

  int row = dataGridView1.CurrentCell.RowIndex + 1;
  int col = dataGridView1.CurrentCell.ColumnIndex + 1;

  if (dataGridView1.Rows.Count == row)
  {
    MessageBox.Show("已是最后一行,无法下移");
    return;
  }

  int count = dataGridView1.ColumnCount;
  for (int i = 0; i < count; i++)
  {
    list.Add(dataGridView1.Rows[row - 1].Cells[col - 1 + i].Value.ToString());
    list1.Add(dataGridView1.Rows[row].Cells[col - 1 + i].Value.ToString());
  }

  for (int j = 0; j < count; j++)
  {

    dataGridView1.Rows[row - 1].Cells[col - 1 + j].Value = list1.ElementAt(j);
    dataGridView1.Rows[row].Cells[col - 1 + j].Value = list.ElementAt(j);
  }

  dataGridView1.Rows[rowIndex].Cells[0].Selected = false;
  dataGridView1.Rows[rowIndex + 1].Cells[0].Selected = true;

  dataGridView1.CurrentCell = dataGridView1.Rows[rowIndex + 1].Cells[0];//这行代码很重要,重新设置当前单元格

}

以上方法是通过单元格之间的数据交换来实现了,最后别忘了重新设置当前单元格,如有其它更好的方法,请各位不吝赐教,谢谢。

 

posted @ 2020-08-12 11:11  Struggle_Rui  阅读(883)  评论(0编辑  收藏  举报