我有一个windows窗体应用程序与一个文本框控件,我想只接受整数值。在过去,我通过重载KeyPress事件并删除不符合规范的字符来进行这种验证。我已经看了MaskedTextBox控件,但我想一个更通用的解决方案,可以与也许正则表达式,或依赖于其他控件的值。

理想情况下,按下非数字字符要么不产生结果,要么立即向用户提供关于无效字符的反馈。


当前回答

您可以使用TextChanged事件

private void textBox_BiggerThan_TextChanged(object sender, EventArgs e)
{
    long a;
    if (! long.TryParse(textBox_BiggerThan.Text, out a))
    {
        // If not int clear textbox text or Undo() last operation
        textBox_LessThan.Clear();
    }
}

其他回答

Here is a simple solution that works for me.

public static bool numResult;
    public static bool checkTextisNumber(string numberVal)
    {
        try
        {
            if (numberVal.Equals("."))
            {
                numResult = true;
            }
            else if (numberVal.Equals(""))
            {
                numResult = true;
            }
            else
            {
                decimal number3 = 0;
                bool canConvert = decimal.TryParse(numberVal, out number3);
                if (canConvert == true)
                {
                    numResult = true;
                }
                else
                    numResult = false;
            }

        }
        catch (System.Exception ex)
        {
            numResult = false;
        }
        return numResult;
    }
    string correctNum;
    private void tBox_NumTester_TextChanged(object sender, TextChangedEventArgs e)
    {


        if(checkTextisNumber(tBox_NumTester.Text))
        {
            correctNum = tBox_NumTester.Text;
        }
        else
        {
            tBox_NumTester.Text = correctNum;
        }

    }

您可以使用TextChanged事件

private void textBox_BiggerThan_TextChanged(object sender, EventArgs e)
{
    long a;
    if (! long.TryParse(textBox_BiggerThan.Text, out a))
    {
        // If not int clear textbox text or Undo() last operation
        textBox_LessThan.Clear();
    }
}

你可以使用TextChanged/ Keypress事件,使用正则表达式过滤数字,并采取一些行动。

这是用.NET 5/Core来实现的一种很好很短的方法

private void textBox1_KeyDown(object sender, KeyEventArgs e) {
  if (e.KeyData != Keys.Back)
    e.SuppressKeyPress = !int.TryParse(Convert.ToString((char) e.KeyData), out int _);
}

编辑:增加了退格键的支持

这正是设计已验证/正在验证事件的目的。

下面是MSDN上关于这个主题的文章:http://msdn.microsoft.com/en-us/library/system.windows.forms.control.validating.aspx

TL;DR版本:检查validate事件中的. text属性,并在数据无效时设置e.Cancel=True。

当你设置e.Cancel=True时,用户不能离开这个字段,但是你需要给他们一些错误的反馈。我将方框的背景颜色更改为浅红色,以表示有问题。确保将其设置回SystemColors。窗口时调用一个良好的值。