Vantalk
Vantalk

Reputation: 376

C# - How can I block the typing of a letter on a key press?

I have a textbox with a OnKeyPress event. In this textbox I wish to input only numbers, and for some specific letters like t or m, I would want to execute a code without that letter being typed in the textbox. Small sample of what I am trying to do:

 //OnKeyPressed:
 void TextBox1KeyDown(object sender, KeyEventArgs e)
    {
        if(e.KeyCode == Keys.T || e.KeyCode == Keys.M) Button1Click(this, EventArgs.Empty);
    }

This unfortunately does not prevent the input of the letter..

Upvotes: 1

Views: 2261

Answers (2)

Anant Dabhi
Anant Dabhi

Reputation: 11104

You could always run the TryParse on the keyDown event so as to validate as the data gets entered. It saves the user an additional UI interaction.

private void TextBox1KeyDown(object sender, KeyEventArgs e)
    {
        int i;

        string s = string.Empty;

        s += (char)e.KeyValue;

         if (!(int.TryParse(s, out i)))
        {
            e.SuppressKeyPress = true;
        }
        else if(e.KeyCode == Keys.T || e.KeyCode == Keys.M)
        {
            e.SuppressKeyPress = true;
            Button1Click(this, EventArgs.Empty);
        }             
    }

Upvotes: 1

Raluca Pandaru
Raluca Pandaru

Reputation: 345

Set the SuppressKeyPress property from KeyEventArgs to true, like below:

private void TextBox1KeyDown(object sender, KeyEventArgs e)
{
    if (e.KeyCode == Keys.T || e.KeyCode == Keys.M)
    {
        e.SuppressKeyPress = true;
        Button1Click(this, EventArgs.Empty);
    }
}

Upvotes: 4

Related Questions