我尝试了一些代码但没有成功
例如我发现了它,但没有用:
if (!char.IsControl(e.KeyChar)
&& !char.IsDigit(e.KeyChar)
&& e.KeyChar != '.')
{
e.Handled = true;
}
// only allow one decimal point
if (e.KeyChar == '.'
&& (sender as TextBox).Text.IndexOf('.') > -1)
{
e.Handled = true;
}
您在这里有一个非常简单但可以理解的错误。
Handled
的KeyPressEventArgs
属性应设置为true,以防止操作系统进一步处理密钥。
换句话说,当您要防止按键时将其设置为true。
因此,当按下的键符合条件时,将这样的代码更改为允许进一步处理。
[另请参阅如何引入布尔变量以使代码可读。
下面的代码允许
祝你好运。>>
private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
{
bool isControl = char.IsControl(e.KeyChar);
bool isDigit = char.IsDigit(e.KeyChar);
bool isDot = e.KeyChar == '.';
bool alreadyHasADot = (sender as TextBox).Text.IndexOf('.') != -1;
bool isHyphen = e.KeyChar == '-';
bool isFirstChar = (sender as TextBox).Text.Length == 0;
bool isAllowed =
isControl ||
isDigit ||
(isDot && !isFirstChar && !alreadyHasADot) ||
(isHyphen && isFirstChar);
if (!isAllowed)
{
e.Handled = true;
}
}