Siwar
Siwar

Reputation: 217

DataGridView, how to capture a cell's KeyPress event C#

i want to do treatement for a cell in datagridview c#, this traitement is open a form when i press a cell.

in C# there isn't an event (keypress) which allows me to add my treatment directly

After search on internet, I found the following solution

 private void dGridView_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e)
    {
        e.Control.KeyPress +=
        new KeyPressEventHandler(Control_KeyPress);
    }


           private void Control_KeyPress(object sender, KeyPressEventArgs e)
        {
            if ((Strings.Asc(e.KeyChar) >= Strings.Asc(Keys.A.ToString()) && Strings.Asc(e.KeyChar) >= Strings.Asc(Keys.Z.ToString())) || (Strings.Asc(e.KeyChar) >= Strings.Asc(Keys.D0.ToString()) && Strings.Asc(e.KeyChar) >= Strings.Asc(Keys.D9.ToString()) || (Strings.Asc(e.KeyChar) >= 97 && Strings.Asc(e.KeyChar) > 122)))
            {
                ------
            }
      }

but it doesn't work. in debug the code of the event dGridView_EditingControlShowing was executed but the code of Control_KeyPress function does not run

any ideas please

Upvotes: 3

Views: 19171

Answers (2)

Just to make the first answer simple. 1) Go to your form's properties 2) Set the 'KeyPreview' to 'True' 3) On your form's Key Press event:

private void Control_KeyPress(object sender, KeyPressEventArgs e)
{
    //your code
}

Upvotes: 2

Dmitrii Dovgopolyi
Dmitrii Dovgopolyi

Reputation: 6301

You should set your Form KeyPreview proprety to true. And you should handle the key pressed event on the main form. That is because Control.KeyPress event

Occurs when a key is pressed while the control has focus. (msdn)

public Form()
{
    InitializeComponent();
    this.KeyPreview = true;
    this.KeyPress += new KeyPressEventHandler(Control_KeyPress);
}

private void Control_KeyPress(object sender, KeyPressEventArgs e)
{
    //your code
}

Upvotes: 7

Related Questions