Home > other >  Disable navigation keys on datagridview cell edit
Disable navigation keys on datagridview cell edit

Time:01-27

I am displaying a list box with suggestion while typing in datagrieview cell. So I want when I press Down Arrow key, focus should go to the first item of list box. But focus is going to below cell of current cell as a default funcationality of datagridview. I have tried this...

private void dgvHP_OPDPrescriptionDiagnosis_Detail____KeyDown(object sender, KeyEventArgs e)
    {
        switch (e.KeyData & Keys.KeyCode)
        {
            case Keys.Up:
            case Keys.Right:
            case Keys.Down:
            case Keys.Left:
                e.Handled = true;
                e.SuppressKeyPress = true;
                break;
        }
    }

It's not working.

CodePudding user response:

The method to override is ProcessDataGridViewKey which is responsible for navigation keys:

public class DataGridView2 : DataGridView
{
    protected override bool ProcessDataGridViewKey(KeyEventArgs e)
    {
        if (e.KeyCode == Keys.Down)
        {
            // return true; // do nothing
            // or
            return false; // pass it to the editing control
        }
        return base.ProcessDataGridViewKey(e);
    }
}

If you passed the key to the editing control, then the next event to handle is EditingControlShowing which raises when the editing control is showing:

private void DataGridView1_EditingControlShowing(object? sender,
    DataGridViewEditingControlShowingEventArgs e)
{
    //Check if the editing column is the one you are interested
    if (dataGridView1.CurrentCell.ColumnIndex == 0)
    {
        var txt = (DataGridViewTextBoxEditingControl)e.Control;
        txt.KeyDown -= Txt_KeyDown;
        txt.KeyDown  = Txt_KeyDown;
    }
}
private void Txt_KeyDown(object? sender, KeyEventArgs e)
{
    if (e.KeyCode == Keys.Down)
    {
        e.Handled = true;
        if (listBox1.SelectedIndex   1 <= listBox1.Items.Count - 1)
        {
            listBox1.SelectedIndex  = 1;
        }
    }
}
  • Related