限制用户仅在C#windows应用程序中输入数字

Nar*_*yan 8 c# winforms

我已经尝试过这段代码来限制数字.当我们尝试输入字符或任何其他控件时,它只键入数字并且不输入,即使它也没有输入退格.如何防止退格.

private void TxtBox1_KeyPress(object sender, KeyPressEventArgs e)
{
     if (!System.Text.RegularExpressions.Regex.IsMatch(e.KeyChar.ToString(), "\\d+"))
          e.Handled = true;
}
Run Code Online (Sandbox Code Playgroud)

Ode*_*ded 28

您不需要使用RegEx来测试数字:

private void TxtBox1_KeyPress(object sender, KeyPressEventArgs e)
{
     if (!Char.IsDigit(e.KeyChar))
          e.Handled = true;
}
Run Code Online (Sandbox Code Playgroud)

允许退格:

private void TxtBox1_KeyPress(object sender, KeyPressEventArgs e)
{
     if (!(Char.IsDigit(e.KeyChar) || (e.KeyChar == (char)Keys.Back)))
          e.Handled = true;
}
Run Code Online (Sandbox Code Playgroud)

如果要添加其他允许的键,请查看Keys枚举并使用上述方法.


Lax*_*nge 8

要仅允许Windows应用程序中文本框中的数字,请使用

private void TxtBox1_KeyPress(object sender, KeyPressEventArgs e)
{
     if (!(Char.IsDigit(e.KeyChar) || (e.KeyChar == (char)Keys.Back)))
          e.Handled = true;
}
Run Code Online (Sandbox Code Playgroud)

此示例代码将允许输入数字和退格键以删除以前输入的文本.


dkn*_*ack 6

使用Char.IsDigit方法(String,Int32)方法并NumericTextbox通过Microsoft 检出

MSDN如何:创建数字文本框


sAc*_*re. 5

将以下代码放在文本框的按键事件中:

     private void txtbox1_KeyPress(object sender, KeyPressEventArgs e)
    {
        e.Handled = !char.IsDigit(e.KeyChar) && !char.IsControl(e.KeyChar);
    }
Run Code Online (Sandbox Code Playgroud)