Trigger key down event when text cell is in focus

502 Views Asked by At

In my DataGridView I make a cell active with

dgw.CurrentCell = dgw.Rows[e.RowIndex].Cells["ColumnHeader"]; 

This way, a user can start type directly into the cell just by press any key. When first key is a plus sign, I want to delete the text in the cell.

How can I catch the key down event? dgw_KeyDown doesn´t work because that event is for the DataGridView itself, but it´s not triggered in this case since a cell is in focus.

1

There are 1 best solutions below

0
Luminous On

You aren't the first to ask this question and here's what I found.

You can't capture what's going on inside the cell because the event you are trying to capture is not associated with the DataGridView. When a cell obtains focus a DataGridViewTextBoxEditingControl encapsulates the selected cell and it is there lies the event you want. The TextChanged event. In combination with the DataGridView's EditingControllShowing event you can capture the text the user has entered as they are typing.

    Private Sub DataGridView1_EditingControlShowing( sender As Object,  e As DataGridViewEditingControlShowingEventArgs) Handles DataGridView1.EditingControlShowing
        AddHandler e.Control.TextChanged, AddressOf CellTextChanged
    End Sub

private sub cellTextChanged(sender as object, e as EventArgs)
    dim textCtrl as DataGridViewTextBoxEditingControl = DirectCast(sender, DataGridViewTextBoxEditingControl)
    console.WriteLine(textCtrl.Text)
end sub

When you leave the cell the DataGridViewTextBoxEditingControl or dgvtbec is cleaned up so there's nothing extra you have to worry about!

Wait! I wanna use the KeyDown event just how my question asked. Why are you not using it? When you use the KeyDown event, the event will be raised when you press any key. That doesn't mean it will raise it after your cell has input changed in it. This means if we were to use the KeyDown event on an empty cell we would still see the cell having no text instead of finding whatever text we inputted if we were to use the TextChanged event.

Related findings (link):

The grid doesn't have a TextChanged event. You aren't editing anything in the grid itself. When you start an editing session a new or existing control of the appropriate type for the cell is embedded in the cell and you edit the data in that. That's why no event is raised in the grid: because nothing changes in the grid until you leave the cell, the editing session ends and the new value is pushed to the cell.