How to handle KeyEvents in a DataGridViewCell?

两盒软妹~` 提交于 2019-12-01 15:48:17

I found this code in a forum, and it works.

private void dataGridView1_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e)
{
  DataGridViewTextBoxEditingControl tb =(DataGridViewTextBoxEditingControl)e.Control;
  tb.KeyPress += new KeyPressEventHandler(dataGridViewTextBox_KeyPress);

  e.Control.KeyPress += new KeyPressEventHandler(dataGridViewTextBox_KeyPress);
}


private void dataGridViewTextBox_KeyPress(object sender, KeyPressEventArgs e)
{
  //when i press enter,bellow code never run?
  if (e.KeyChar==(char)Keys.Enter)
  {
    MessageBox.Show("You press Enter");
  }
}

DataGridViewCell doesn’t have any events, but you can listen for the KeyDown event on the DataGridView itself and then look at which cell is selected:

public void dataGridView_KeyDown(object sender, KeyEventArgs e)
{
    if (e.KeyCode == Keys.F1)
    {
        var selectedCell = dataGridView.SelectedCells[0];
        // do something with selectedCell...
    }
}

When the user types into a cell it is actually typing into the control that is placed inside the cell for editing purposes. For example, a string column type will actually create a TextBox for use inside the cell for the user to input against. So you need to actually hook into the KeyDown event of the TextBox that is placed inside the cell when editing takes place.

I know this is an old question, but I believe I have improved upon the top voted answer.

    IDataGridViewEditingControl _iDataGridViewEditingControl;
    private void SlotTimesDGV_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e)
    {
        if (_iDataGridViewEditingControl is DataGridViewComboBoxEditingControl)
        {
            DataGridViewComboBoxEditingControl iDataGridViewEditingControl = _iDataGridViewEditingControl as DataGridViewComboBoxEditingControl;
            iDataGridViewEditingControl.KeyPress -= SlotTimesDGV_EditingControlShowing_KeyPress;
        }
        if (e.Control is DataGridViewComboBoxEditingControl)
        {
            DataGridViewComboBoxEditingControl iDataGridViewEditingControl = e.Control as DataGridViewComboBoxEditingControl;
            iDataGridViewEditingControl.KeyPress += SlotTimesDGV_EditingControlShowing_KeyPress;
            _iDataGridViewEditingControl = iDataGridViewEditingControl;
        }
    }

    private void SlotTimesDGV_EditingControlShowing_KeyPress(object sender, KeyPressEventArgs e)
    {
        MessageBox.Show("");
    }

By having an instance variable of the IDataGridViewEditingControl, you can remove the KeyPress event that would result in duplicate calls when moving around cells and your event is not limited to only one type of cell.

Federico Sanchez

another solution is

private void grdDetalle_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e)
    {
        // Sólo queremos esta funcionalidad para determinadas columnas Clave y Nombre
        if ((grdDetalle.Columns[grdDetalle.CurrentCell.ColumnIndex].Name == "colClaveArticulo") ||
            (grdDetalle.Columns[grdDetalle.CurrentCell.ColumnIndex].Name == "colNombre"))
        {
            /// Workarround para que estando editando en las columnas del grid Clave y Nombre
            /// podamos detectar cuando se dio F4 para lanzar el dialogo de busqueda del
            /// articulo.
            e.Control.KeyDown += new KeyEventHandler(dataGridViewTextBox_KeyDown);
            e.Control.Leave += new EventHandler(dataGridViewTextBox_Leave);
        }
    }

    private void dataGridViewTextBox_Leave(object sender, EventArgs e)
    {

        if ((grdDetalle.Columns[grdDetalle.CurrentCell.ColumnIndex].Name == "colClaveArticulo") ||
           (grdDetalle.Columns[grdDetalle.CurrentCell.ColumnIndex].Name == "colNombre"))
        {
            try
            {
                (sender as DataGridViewTextBoxEditingControl).KeyDown -= 
                   new KeyEventHandler(dataGridViewTextBox_KeyDown);
            }
            catch (Exception ex)
            { }
        }
    }

    private void dataGridViewTextBox_KeyDown(object sender, KeyEventArgs e)
    {
        // F4 Pressed
        if ((grdDetalle.Columns[grdDetalle.CurrentCell.ColumnIndex].Name == "colClaveArticulo") ||
           (grdDetalle.Columns[grdDetalle.CurrentCell.ColumnIndex].Name == "colNombre"))
        {
            if (e.KeyCode == Keys.F4) // 115
            {
                MessageBox.Show("Oprimieron F4");
                e.Handled = true;
                e.SuppressKeyPress = true;
            }
        }
    }
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!