我已经解决了这个问题(使用另一种方法)。但是仍然不知道为什么下面的方法不起作用。请帮忙
目的:当从一个文本框离开时,检查它是否只包含数字-然后允许离开。如果不显示错误提供程序。检查字符串长度是否不超过 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();
}