C# 如何获得 BackSpace - 文本框中只有数字限制?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1523895/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-06 18:23:50  来源:igfitidea点击:

How to get BackSpace - with only numbers limit in textbox?

c#winforms

提问by Gold

I insert this on KeyPressevent:

我在KeyPress事件中插入这个:

e.Handled = !Char.IsNumber(e.KeyChar);

But I don't have the Backspacekey, how to fix it?

但是我没有Backspace钥匙,怎么修?

采纳答案by Jon Skeet

How about:

怎么样:

e.Handled = !(Char.IsNumber(e.KeyChar) || e.KeyChar == 8);

Or equivalently:

或等效地:

e.Handled = !Char.IsNumber(e.KeyChar) && e.KeyChar != 8;

(As in roman's answer, you can use '\b'instead of 8 in the above code too.)

(在roman's answer 中,您也可以'\b'在上面的代码中使用8 代替。)

回答by roman m

here's how to check if backspace was pressed:

以下是检查是否按下退格键的方法:

if(e.KeyChar == '\b'){//backspace was pressed}

回答by anfd

backspace key
e.KeyChar == (char) Keys.Back

退格键
e.KeyChar == (char) Keys.Back