仅为Numbers屏蔽文本框但不接受BackSpace

时间:2009-06-29 22:06:37

标签: c# winforms masking

我有一个文本框,我只想要数字。但如果我打错了号码,我就无法退格以纠正它。如何允许退格键工作。感谢

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

9 个答案:

答案 0 :(得分:3)

您可以添加一项检查以允许控制字符:

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

更新:回应person-b对代码的评论/他建议采用以下风格(这也是我个人写的方式):

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

答案 1 :(得分:3)

正确答案是:

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

答案 2 :(得分:1)

您还可以覆盖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();
}

请注意,您必须添加代码才能设置插入位置。

答案 3 :(得分:0)

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

答案 4 :(得分:0)

以上格式略微清晰:

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

答案 5 :(得分:0)

我发现以下效果很好。它包括允许退格,箭头键删除键等的额外例外。 How to allow only numeric (0-9) in HTML inputbox using jQuery?

答案 6 :(得分: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;
    }
}

参考链接:Masking Textbox to accept only decimals小数/ 12209854#12209854

答案 7 :(得分:0)

您可以在按键事件中使用以下内容:

      private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
    {
        if (!Char.IsDigit(e.KeyChar) & (e.KeyChar != 8)) e.Handled = true; 
    }

答案 8 :(得分:-1)

按下您的文本框,然后输入事件 从事件双击 KeyPress 然后写下这段代码

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