Reputation: 111
im having a datagridview, now my requirement is that when the use edits the cell and clicks the enter or tabg key, the new cell value should be updated in to the database, im able to update the new value in to database, i have written my code in keyup event of datagridview, now in the keyup event when the user presses the enter key, the control is moving to the next row, so im getting the row index value as actualrowindex+1, also when i click tab key, the control is moving the next column, so im getting the column index as columnindex+1, how can i handle these eventst o get the exact column index or rowindex when i click enetr or tab key?..below is teh event in whichj i wrote my code..
private void dataGridView1_KeyUp(object sender, KeyEventArgs e)
{
}
Upvotes: 0
Views: 2212
Reputation: 244981
It's pointless to handle the Enter and Tab keys when there are lots of other ways for a user to commit a change to a cell's value. For example, they can click on another cell. Presumably you wish to have the database updated when they do one of these other things as well, not just when they press certain keys.
So instead of handling the KeyUp
event, handle the CellValueChanged
event. This event is raised whenever the user commits a change made to a cell's value, which typically occurs when focus leaves the cell.
As you point out, pressing Enter causes the focus to shift to the next cell in the column, while Tab causes the focus to shift to the next cell in the row, so this will work just fine in your case. It will also work when the user clicks on another cell using the mouse, or moves around to another cell using the arrow keys, or any of a number of other methods of committing a change.
When you handle this event, you will always get the correct row index and column index for the changed cell. This information is contained in the DataGridViewCellEventArgs
object passed as the e
parameter to the event handler method.
Upvotes: 2