Masking a text box for numbers only, but don't accept backspace

I have a text box that I would like to use only for numbers. But if I dial the wrong number, I can’t cancel it to fix it. How can I let backspaces work. Thanks

    private void amount_PaidTextBox_KeyPress(object sender, KeyPressEventArgs e)
    {
        if (Char.IsNumber(e.KeyChar) != true)
        {
            e.Handled = true;
        }
    }
+3
source share
7 answers

You can also add a check to be able to control characters:

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

Update: In response to man-b's comment on s / he code, he offers the following style (which I would also personally write):

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

Correct answer:

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

TextChanged:

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

, , .

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

:

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

, . , backspace, .. (0-9) HTML jQuery?

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

. : /12209854 # 12209854

0

Source: https://habr.com/ru/post/1711522/


All Articles