[英]C# - e.KeyChar != '.' not working
In my Windows Forms application I have a TextBox and applied to it the KeyPress event to accept just numbers. 在我的Windows窗体应用程序中,我有一个TextBox并将其应用于KeyPress事件以仅接受数字。 In the moment, my script is this way:
目前,我的脚本是这样的:
if (!char.IsControl(e.KeyChar)
&& !char.IsDigit(e.KeyChar)
&& e.KeyChar != '.')
{
e.Handled = true;
}
The problem is that in e.KeyChar != '.'
问题在于
e.KeyChar != '.'
it doesn't work, my TextBox is accepting numbers and dots. 它不起作用,我的TextBox接受数字和点。 I don't understand why because I say to the script that if the pressed key be different of dot (.), then doesn't input it.
我不明白为什么,因为我对脚本说,如果所按的键与点(。)不同,则不会输入。 Some examples of values I'm receiveing are:
我收到的一些值的示例是:
!=
doesn't do anything there. !=
在那里什么也不做。 Unless I am missing something, wouldn't it make more sense to check for what is acceptable rather than what isn't? 除非我失去了一些东西,那岂不是更有意义检查什么是可以接受,而不是什么没有?
e.Handled = !(char.IsControl(e.KeyChar) || char.IsDigit(e.KeyChar) || e.KeyChar == '.');
This is by no means a complete solution however because this would still allow values like 12345.67.89.
但是,这绝不是一个完整的解决方案,因为它仍然允许像
12345.67.89.
这样的值12345.67.89.
which obviously aren't numerically formatted correctly. 显然,其数字格式不正确。
A more robust solution would be to use a MaskedTextBox or allow freetext but validate the entire input rather then each individual char
. 一个更可靠的解决方案是使用MaskedTextBox或允许自由文本,但先验证整个输入,然后验证每个单独的
char
。
Even better solution. 更好的解决方案。 With this one you can only use: 0123456789 and backspace
使用此功能,您只能使用:0123456789和退格键
if (!char.IsDigit(e.KeyChar) && e.KeyChar != '\b')
e.Handled = true
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.