我想限制用户在 TextBox 中只键入数字。 我在按键事件中添加此代码:
private void txtPartID_KeyPress(object sender, KeyPressEventArgs e)
{
if (((e.KeyChar >= '0') && (e.KeyChar <= '9')) == false)
{
e.Handled = true;
}
}
但此后 BackSpace 键不适用于此 TextBox。我该如何更改?
最佳答案
你可以用这个检查退格键,
if(e.KeyChar == '\b')
只检查数字的更好方法是
private void txtPartID_KeyPress(object sender, KeyPressEventArgs e)
{
e.Handled = !(Char.IsNumber(e.KeyChar) || e.KeyChar == 8);
}
关于c# - C# 中 WinForm TextBox 中数字的按键事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29092456/