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

后端 未结 7 1941
鱼传尺愫
鱼传尺愫 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 09:16

    For me this worked:

     public static void MoveUp(DataGridView dgv)
        {
            if (dgv.RowCount <= 0)
                return;
    
            if (dgv.SelectedRows.Count <= 0)
                return;
    
            var index = dgv.SelectedCells[0].OwningRow.Index;
    
            if (index == 0)
                return;
    
            var rows = dgv.Rows;
            var prevRow = rows[index - 1];
            rows.Remove(prevRow);
            prevRow.Frozen = false;
            rows.Insert(index, prevRow);
            dgv.ClearSelection();
            dgv.Rows[index - 1].Selected = true;
        }
    
        public static void MoveDown(DataGridView dgv)
        {
            if (dgv.RowCount <= 0)
                return;
    
            if (dgv.SelectedRows.Count <= 0)
                return;
    
            var rowCount = dgv.Rows.Count;
            var index = dgv.SelectedCells[0].OwningRow.Index;
    
            if (index == rowCount - 1) // Here used 1 instead of 2
                return;
    
            var rows = dgv.Rows;
            var nextRow = rows[index + 1];
            rows.Remove(nextRow);
            nextRow.Frozen = false;
            rows.Insert(index, nextRow);
            dgv.ClearSelection();
            dgv.Rows[index + 1].Selected = true;
        }
    

    The difference to Mario's code is that I used (rowCount - 1) instead of (rowCount - 2) ... After changing this, it worked perfectly. Before the move-down didn't work if you only have 2 rows in your DataGridView...

提交回复
热议问题