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

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

\"enter

  1. The user selects one row
  2. there will be up arrow and down arrow.
相关标签:
7条回答
  • 2020-12-11 09:19

    Cleaned the code of Jegan and made it suitable for multiple datagridviews.

        private 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;
        }
    
        private 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 - 2)) // include the header row
                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;
        }
    
    0 讨论(0)
提交回复
热议问题