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

后端 未结 7 1975
鱼传尺愫
鱼传尺愫 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:11

    Here is a very small solution for that issue:

        private void DataGridView_KeyDown(object sender, KeyEventArgs e)
        {
            //I use only one function for moving with the information
            //e.KeyCode == Keys.Up = move up, else move down
            if (e.KeyCode.Equals(Keys.Up) || e.KeyCode.Equals(Keys.Down))
            {
                MoveUpDown(e.KeyCode == Keys.Up);
            }
            e.Handled = true;
        }
    
        private void MoveUpDown(bool goUp)
        {
            try
            {
                int currentRowindex = DataGridView.SelectedCells[0].OwningRow.Index;
    
                //Here I decide to change the row with the parameter
                //True -1 or False +1
                int newRowIndex = currentRowindex + (goUp ? -1 : 1);
    
                //Here it must be ensured that we remain within the index of the DGV
                if (newRowIndex > -1 && newRowIndex < DataGridView.Rows.Count)
                {
                    DataGridView.ClearSelection();
                    DataGridView.Rows[newRowIndex].Selected = true;
                }
            }
            catch (Exception)
            {
                MessageBox.Show("Error");
            }
    
        }
    

    Sorry, I thought my code was self-explanatory. I hope I made with the comments clear how I proceeded with that issue

提交回复
热议问题