简体   繁体   中英

Masking a textbox for Numbers only but wont accept BackSpace

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;
        }
    }

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;
}

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));
 }
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; 
    }

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?

Press on the your textbox then enter the events From events double click on KeyPress And then write this code

if( e.KeyChar <'0' || e.KeyChar > '9' )
if(e.KeyChar!=08)
e.Handled=true;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM