1
votes

I've a weird situation while keyboard shortcuts of a button along with datagridview is used. Here is the explanation:

I've a winform in which there is a datagridview and a save button. Save button has keyboard shortcut Alt+S. I enter some rows in the grid and I validate all the cells on Save button click and if cell value is invalid then I'll set the focus to that cell. Here is the code used to achieve that:

  for (var index = 0; index < GridView.Rows.Count; index++)
  {
    var itemRow = GridView.Rows[index];

    if (itemRow.Cells[SomeColumn.Name].Value.ToString() == string.Empty)
    {
       GridView.CurrentCell = itemRow.Cells[SomeColumn.Name];
       GridView.Focus();
    }
  }

Above code works fine and sets the focus in the particular cell with cursor when I click on the save button.

But, when I use shortcut key, focus is not set to the cell at all. I'm not sure why it is behaving like this.

Out of curiosity I've tested an event of the datagridview. CellLeave event of datagridview is fired when I click on save button, but when I use shortcut for save button it doesn't get fired.

Why is it behaving like this? any inputs? How can I set the focus when I use shortcuts?

Update: I've done a trick to work it properly. I've added SaveButton.Focus() code in the button click event of the save button as first line. This is redundant but forcing the grid to lose the focus when user uses short cut key to access this button. This solution is working fine, but not sure what could be the reason for the above situation. Still looking for an answer. :(

1
May sound like a stupid question but it's just to be sure: Is the button click event triggered when you use the shortcut ?Jla
Based on the CellLeave event test, I'm guessing that Grid is not even losing focus hence particular cell focus may not be working properly, this is just a guess but there is no reason for why cell focus not working even in this case.JPReddy

1 Answers

1
votes

Check the key combination on DataGridVeiw keyDown event then if the key is Alt+S then set focus to DatagridVeiw

Updated:

 private void dataGridView1_KeyDown(object sender, KeyEventArgs e)
 {
    if (e.KeyData == (Keys.Alt | Keys.S))
    {
         //put your code to validate i.e. what u are trying in button click event
    }
 }