检查文本框是否仅包含数字

时间:2013-05-12 05:25:18

标签: c# validation textbox

我已经完成了这个问题(使用替代方法)。但仍然不知道为什么以下方法不起作用。请帮忙

目标:从文本框离开时      检查它是否只包含数字 - 然后允许离开。      如果没有显示错误提供程序。      检查字符串长度是否不超过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();
}

1 个答案:

答案 0 :(得分:0)

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

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

}

如果属实,请使用break;

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

}

更多建议..

  1. 具有名为MaxLength的属性的TextBox控件,您可以将其设置为7以限制用户输入最多7个字符
  2. 如果您只需要允许数字不使用int.TryParse方法。如果带小数点的输入将通过验证。
  3. 检查字符串只包含可以使用if (textBox1.Text.ToCharArray().Any(c=>!Char.IsDigit(c)))
  4. 等代码的数字
  5. 如果验证失败,则需要设置e.Cancel = true;
相关问题