1

I (I am fairly new at C#) ran into a problem which I have tried to solve myself but couldn't find a solution.

given: I have a Datagridview with 10 columns and x rows. (The column Headers reach from 1 to 10)

My Problem: I only need to write "1", "0" or "=" into the cells, but for more filling speed while using the Numpad I would like to automatically write a "=" into the current selected cell when I press 2 on the Numpad.

My Current solution (Which doesn't work):

private void dataGridView1_KeyPress(object sender, KeyPressEventArgs e)
{
   if(e.KeyChar == '2'||e.KeyChar.ToString() == "2")
   {
      dataGridView1.Rows[dataGridView1.CurrentCell.RowIndex].Cells[dataGridView1.CurrentCell.ColumnIndex].Value = "=";
   }
}

I have tried it with cellLeave and cellstatchanged but it doesn't work.

Jason Aller
  • 3,541
  • 28
  • 38
  • 38
HCCFMT
  • 11
  • 1
  • What doesn't work? Is the keypress not being captured? are you unable to get the correct cell? Is the value not being entered into the cell. Also,the DataGridView class has a CurrentCell property. – User92 Jul 24 '15 at 09:21

3 Answers3

1

You didn't reply to my comment, but I'm guessing that this isn't working because the event isn't being captured. When the datagridview is in edit mode, the cells editing control receives the key event, not the datagridview.

Try adding an event handler for the EditingControlShowing event, and then use the control property of the event args to add an event handler for its key events.

E.g

    private void dataGridView1_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e)
    {
        var ctrl = e.Control as TextBox;
        if (ctrl == null) return;

        ctrl.KeyPress += Ctrl_KeyPress;
    }

    private void Ctrl_KeyPress(object sender, KeyPressEventArgs e)
    {
        // Check input and insert values here...
    }
User92
  • 326
  • 1
  • 6
0

Refer the below code :

if (e.KeyChar == (char)Keys.NumPad2 || e.KeyChar == (char)Keys.Oem2)
{
     dataGridView1.Rows[dataGridView1.CurrentCell.RowIndex].Cells[dataGridView1.CurrentCell.ColumnIndex].Value = "=";
}

Hope this will work for you.

Saragis
  • 1,782
  • 6
  • 21
  • 30
0

You can try this method using the DataGridView.KeyDown event :

private void dataGridView1_KeyDown(object sender, KeyEventArgs e)
{
    if (e.KeyCode == Keys.NumPad2) {
        this.CurrentCell.Value = "=";
    }
}
Ilshidur
  • 1,461
  • 14
  • 11