本文介绍了C#中WinForm TextBox中数字的keypress事件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想限制用户仅在TextBox中键入数字.我在按键事件中添加此代码:
I want to limit user to type just numbers in TextBox.I add this code In keypress Event:
private void txtPartID_KeyPress(object sender, KeyPressEventArgs e)
{
if (((e.KeyChar >= '0') && (e.KeyChar <= '9')) == false)
{
e.Handled = true;
}
}
,但是在此之后,BackSpace键不适用于此TextBox.我该如何更改?
but after that BackSpace key don't work for this TextBox. How can I change this?
推荐答案
您可以使用此方法检查退格,
You can check for backspace using this,
if(e.KeyChar == '\b')
一种更好的仅检查数字的方法是
And better way to check only for numbers is
private void txtPartID_KeyPress(object sender, KeyPressEventArgs e)
{
e.Handled = !(Char.IsNumber(e.KeyChar) || e.KeyChar == 8);
}
这篇关于C#中WinForm TextBox中数字的keypress事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!