How to move gridview selected row up/down on KeyUp or Keydown press

后端 未结 7 1942
鱼传尺愫
鱼传尺愫 2020-12-11 08:19

\"enter

  1. The user selects one row
  2. there will be up arrow and down arrow.
7条回答
  •  -上瘾入骨i
    2020-12-11 08:59

    If you want to move the selected row up/down as many times as you want, you can use this code to move:

    Up:

    if (dataGridView1.SelectedRows[0].Index != 0) {
      for (int j = 0; j < this.dataGridView1.Columns.Count; j++) {
        object tmp = this.dataGridView1[j, dataGridView1.SelectedRows[0].Index].Value;
        this.dataGridView1[j, dataGridView1.SelectedRows[0].Index ].Value = this.dataGridView1[j, dataGridView1.SelectedRows[0].Index - 1].Value;
        this.dataGridView1[j, dataGridView1.SelectedRows[0].Index - 1].Value = tmp;
      }
      int a = dataGridView1.SelectedRows[0].Index;
      dataGridView1.ClearSelection();
      this.dataGridView1.Rows[a - 1].Selected = true;
    }
    

    Down:

     if (dataGridView1.SelectedRows[0].Index != dataGridView1.Rows.Count - 2) {
       for (int j = 0; j < this.dataGridView1.Columns.Count; j++) {
         object tmp = this.dataGridView1[j, dataGridView1.SelectedRows[0].Index].Value;
         this.dataGridView1[j, dataGridView1.SelectedRows[0].Index].Value = this.dataGridView1[j, dataGridView1.SelectedRows[0].Index + 1].Value;
         this.dataGridView1[j, dataGridView1.SelectedRows[0].Index + 1].Value = tmp;
       }
       int i = dataGridView1.SelectedRows[0].Index;
       dataGridView1.ClearSelection();
       this.dataGridView1.Rows[i + 1].Selected = true;
     }
    

提交回复
热议问题