0

我已经解决了这个问题(使用另一种方法)。但是仍然不知道为什么下面的方法不起作用。请帮忙

目的:当从一个文本框离开时,检查它是否只包含数字-然后允许离开。如果不显示错误提供程序。检查字符串长度是否不超过 7 而不是 0 - 然后允许离开。如果不显示错误提供程序。

下面给出了似乎不起作用的代码!:

private void textBox24_Validating(object sender, CancelEventArgs e)
{
bool result = true;

        foreach (char y in textBox24.Text)
        {
            while (y < '0' || y > '9')
                result = false;
        }

        if (result == false)
        {
            errorProvider4.SetError(textBox24, "Enter digits only");
            textBox24.Focus();
        }
        else if (textBox24.Text.Length == 0)
        {
            errorProvider4.SetError(textBox24, "Enter the value");
            textBox24.Focus();
        }
        else if (textBox24.Text.Length > 7)
        {
            errorProvider4.SetError(textBox24, "Maximum length is 7 digits");
            textBox24.Focus();
        }
        else
            errorProvider4.Clear();
}

这段代码的问题:

当我输入数字以外的输入时,它会卡住。可能这不会是一个大问题。不过帮帮我。

我现在使用的代码:

private void textBox24_Validating(object sender, CancelEventArgs e)
{
int check = 123;
        bool result = int.TryParse(textBox24.Text, out check);
        if (result == false)
        {
            errorProvider4.SetError(textBox24, "Only digits are allowed");
            textBox24.Focus();
        }
        else if (textBox24.Text.Length > 7)
        {
            errorProvider4.SetError(textBox6, "Invalid value");
            textBox24.Focus();
        }
        else
            errorProvider4.Clear();
}
4

1 回答 1

0

在while循环中,如果条件为真,则将结果设置为真,但循环将永远运行,因为条件再次为真。

foreach (char y in textBox24.Text)
{
  while (condition) // this is run forever if true
      result = false;

}

你可以使用break;if true case 如下

foreach (char y in textBox24.Text)
{
  while (condition){ 
      result = false;
      break;
   }

}

还有一些建议..

  1. 具有称为属性的 TextBox 控件MaxLength可以将其设置为 7 以限制用户输入最多 7 个字符
  2. 如果您只需要允许数字,请不要使用int.TryParse方法。如果带小数点的输入将通过验证。
  3. 检查字符串仅包含数字,您可以使用类似的代码if (textBox1.Text.ToCharArray().Any(c=>!Char.IsDigit(c)))
  4. 如果验证失败,您需要设置e.Cancel = true;
于 2013-05-12T05:34:52.027 回答