Sunday, August 30, 2009

How to listen for KeyPress events in a DataGridView

When listening to KeyPress events in a DataGridView, you will only listen to events when the actual DataGridView control has focus, and not when you are typing text in a column (e.g. DataGridViewTextBoxColumn) in the grid.
If you want to listen to key events (or any event) in the column, you need to first listen to an event that will fire when the DataGridViewTextBoxColumn control is entering editing mode.

FooDataGridView += DataGridViewEditingControlShowingEventHandler(FooDataGridView_EditingControlShowing);

Then you will be able to listen for the KeyPress event:

private TextBox areaValueTextBox = null;

void FooDataGridView_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e)
{
    if (e.Control is TextBox)
    {
        if (areaValueTextBox == null)
        {
            areaValueTextBox = e.Control as TextBox;
            areaValueTextBox.KeyPress += new KeyPressEventHandler(areaValueTextBox_KeyPress);
        }
        else
            areaValueTextBox = e.Control as TextBox;
    }
}

void areaValueTextBox_KeyPress(object sender, KeyPressEventArgs e)
{
    System.Diagnostics.Debug.WriteLine("==> " + areaValueTextBox.Text + e.KeyChar.ToString());
}
If we didn't create a TextBox object, and instead created a TextBox each time we entered the method, then would we create a new event handler each time, and every event handled would be called, not just newly created. One problem though, is that the KeyPress event will not be fired when tab or return is pressed. One way to solve this problem is to listen to the cell's begin and end edit events. The CellBeginEdit event will be fired when the user start to edit the cell, e.g. by pressing F2, and the CellEndEdit is fired when user hits tab or return.

FooDataGridView.CellBeginEdit += new DataGridViewCellCancelEventHandler(FooDataGridView_CellBeginEdit);
FooDataGridView.CellEndEdit += new DataGridViewCellEventHandlerFooDataGridView_CellEndEdit);
void FooDataGridView_CellBeginEdit(object sender, DataGridViewCellCancelEventArgs e)
{
    System.Diagnostics.Debug.WriteLine("Start edit...");
}
void FooDataGridView_CellEndEdit(object sender, DataGridViewCellEventArgs e)
{
    System.Diagnostics.Debug.WriteLine("...end edit.");
}

No comments:

Post a Comment