Ari
Ari

Reputation: 1036

Preventing textbox value from changing

How do I prevent a textbox value from changing after a certain keypress? For example, I'm trying to prevent numbers from being input, if a number is input a message box is displayed however the number is still being printed. How can I get it so the number is not printed?

private void textBox_KeyPress(object sender, KeyPressEventArgs e)
{
    if (e.KeyChar == '1')
    {
        MessageBox.Show("Only letters please");
    }
}

Thanks in advance, Ari

Upvotes: 1

Views: 731

Answers (4)

V4Vendetta
V4Vendetta

Reputation: 38210

You can use the KeyPress event of the textbox and achieve only letters

void textBox1_KeyPress(object sender, KeyPressEventArgs e)
{
     //allow backspace in case to remove some
     e.Handled = !(char.IsLetter(e.KeyChar) || e.KeyChar == (char)Keys.Back);
}

Upvotes: 0

Magnus Backeus
Magnus Backeus

Reputation: 2296

First I recommend really thinking through the decision to having the client doing a server request every time a key is pressed. Or maybe this is client side validating? A Better option if you want to validate each letter. If so... here is some scripts that can be used (not mine... just googled): http://www.java2s.com/Code/JavaScript/Form-Control/AllowingOnlyNumbersintoaTextBox.htm http://justins-fat-tire.blogspot.com/2007/09/javascript-numeric-only-text-box.html

A good candidate solution may be that you validate this when submitting. Then you minimize amount of server requests.

/Cheers Magnus

Upvotes: 0

Vano Maisuradze
Vano Maisuradze

Reputation: 5899

Here is the sample:

private void textBox_KeyPress(object sender, KeyPressEventArgs e)
{
    if (char.IsDigit(e.KeyChar))
    {
        e.Handled = true;
    }
}

Upvotes: 1

Don Tomato
Don Tomato

Reputation: 3519

private void textBox1_TextChanged(object sender, EventArgs e)
{
    if (Regex.IsMatch(textBox1.Text, "[0-9]"))
    {
        MessageBox.Show("Only letters please");
        textBox1.Text = Regex.Replace(textBox1.Text, "[0-9]", String.Empty);
    }
}

Upvotes: 2

Related Questions