在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];//這行代碼很重要,重新設置當前單元格

}

以上方法是通過單元格之間的數據交換來實現了,最后別忘了重新設置當前單元格,如有其它更好的方法,請各位不吝賜教,謝謝。

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM