检测文本框中的无效数字

问题描述 投票:0回答:2

我正在开发Windows窗体应用程序。我的一个文本框假设接收一个数值以供进一步处理。输入可以是圆数或带小数点的数字。如果用户输入number, backspace key or a dot(".")以外的无效字符,则会出现带警告的标签。这是我的代码:

private void TextBoxMainManualCpkVal_KeyPress(System.Object sender, System.Windows.Forms.KeyPressEventArgs e)
{
    if ((!IsNumeric(e.KeyChar) && e.KeyChar != ControlChars.Back && e.KeyChar != "."))
    {
        LabelWarnMainCpk.Visible = true;
        e.KeyChar = null;
    }
    else
    {
        LabelWarnMainCpk.Visible = false;
    }
}

有效案例:Valid Input

无效案例:Invalid Input where I entered 1.2"w". Letter "w" is INVALID

现在,我想确保用户输入一个有趣的数值,如"1.2.3"警告标签应显示。

目前:Invalid Input That Does Not Shows the warning label

我如何实现这一目标?

c# textbox numeric
2个回答
3
投票

对于Windows窗体应用程序,您可以使用屏蔽输入以确保该用户只能输入允许他通过掩码输入的值。像这样 - 5个数字,一个点,以及之后的两个数字

enter image description here

它在输出中看起来像这样:

enter image description here


0
投票

使用正则表达式:

var regex = new Regex(@"^[0-9]([.,][0-9]{1,3})?$", RegexOptions.IgnoreCase);
var match = regex.Match(inputString);
bool isValid = match != null && match.Success;

stackoverflow中的替代解决方案:

bool IsDecimalFormat(string input) {
  Decimal dummy;
  return Decimal.TryParse(input, out dummy);
}
© www.soinside.com 2019 - 2024. All rights reserved.