0
Answer

DataGridView KeyPress Event Not Working

Ask a question

I want to capture keyboard input and display it in a textbox the same way that, in Excel when you type into a cell, your text appears in the box at the top. I've tried the following code with weird results. The problem is that the input string variable accumulates KeyChar input in odd ways. The correct input is parsed; it's just not displaying properly in textBox1. As you can see, I've tried everything I can think of to clear out both 'input' and textBox1 with no luck.


public partial class Form1 : Form
{
    string input;
    public Form1()
    {
        InitializeComponent();
    }
    void dataGridView1_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e)
    {
        dataGridView1.EditingControl.KeyPress += new KeyPressEventHandler(EditingControl_KeyPress);
        dataGridView1.EditingControl.KeyDown += new KeyEventHandler(EditingControl_KeyDown);
        e.Control.KeyPress += new KeyPressEventHandler(dataGridView1_KeyPress);
    }
    void EditingControl_KeyPress(object sender, KeyPressEventArgs e)
    {
        input += e.KeyChar.ToString();
        textBox1.Text = input;
    }
    private void dataGridView1_CellParsing(object sender, DataGridViewCellParsingEventArgs e)
    {
        input = String.Empty;
        textBox1.Text = input;
        textBox1.Text = e.Value.ToString();
    }
}