Question

I have a textbox that I would like for only numbers. But if I hit the wrong number, I cant backspace to correct it. How can I allow backspaces to work. Thanks

    private void amount_PaidTextBox_KeyPress(object sender, KeyPressEventArgs e)
    {
        if (Char.IsNumber(e.KeyChar) != true)
        {
            e.Handled = true;
        }
    }
Was it helpful?

Solution

You could add a check to allow control characters as well:

if (Char.IsControl(e.KeyChar) != true && Char.IsNumber(e.KeyChar) != true)
{
    e.Handled = true;
}

Update: in response to person-b's comment on the code s/he suggests the following style (which is also how I would personally write this):

if (!Char.IsControl(e.KeyChar) && !Char.IsNumber(e.KeyChar))
{
    e.Handled = true;
}

OTHER TIPS

Correct answer is:

private void amount_PaidTextBox_KeyPress(object sender, KeyPressEventArgs e)
{
    e.Handled = !сhar.IsNumber(e.KeyChar) && (e.KeyChar != '\b');
}

You can also override the TextChanged-event:

private void textBox1_TextChanged(object sender, EventArgs e)
{
    string text = (sender as TextBox).Text;

    StringBuilder builder = new StringBuilder(String.Empty);

    foreach (char character in text)
    {
        if (Char.IsDigit(character))
        {
            builder.Append(character);
        }
    }

    (sender as TextBox).Text = builder.ToString();
}

Please note that you would have to add in code to set the caret position.

private void amount_PaidTextBox_KeyPress(object sender, KeyPressEventArgs e)
{
     if (!Char.IsNumber(e.KeyChar) && e.KeyCode != Keys.Back)
          e.Handled = True;
}

A slightly cleaner format of the above:

 private void amount_PaidTextBox_KeyPress(object sender, KeyPressEventArgs e)
 {
   e.Handled = !(Char.IsNumber(e.KeyChar) || (e.KeyChar==Keys.Back));
 }

I found the following worked well. It included extra exceptions for allowing backspace, arrow keys delete key etc. How to allow only numeric (0-9) in HTML inputbox using jQuery?

private void txt_KeyPress(object sender, KeyPressEventArgs e)
{
    if (Char.IsDigit(e.KeyChar) || e.KeyChar == '\b')
    {
        // Allow Digits and BackSpace char
    }        
    else
    {
        e.Handled = true;
    }
}

Refer Link also: Masking Textbox to accept only decimals decimals/12209854#12209854

You can use the following on Key Press event:

      private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
    {
        if (!Char.IsDigit(e.KeyChar) & (e.KeyChar != 8)) e.Handled = true; 
    }
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top