文本框只接受点 ( . ) 和破折号 ( - )

Textbox Only Accepts Dot( . ) And Dash( - )

我尝试了一些代码但没有用

例如 我找到了这个但没有用:

        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;
    }

你有一个非常简单但可以理解的错误。

KeyPressEventArgsHandled 属性 应设置为 true 以防止操作系统进一步处理密钥。

https://docs.microsoft.com/en-us/dotnet/api/system.windows.forms.keypresseventargs?view=netframework-4.8

换句话说,当您想要阻止密钥时,将此设置为 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;
        }
    }