0

I am checking a text box for the following

  • If there is no input
  • If the input is between 0 and 100
  • If the input is a string other than a number

The code -

if (this.BugCompPct.Text == String.Empty)      
else if (Convert.ToInt32(this.BugCompPct.Text) > 100 | Convert.ToInt32(this.BugCompPct.Text) < 0)
//Not sure about checking the last if

What could I put as the if conditional to check for a string other than an integer? I want only the input to be an integer and nothing else

Thanks

4

4 回答 4

3

我可以把什么作为 if 条件来检查除整数以外的字符串?

使用int.TryParse方法查看解析是否成功。

对于空字符串使用string.IsNullOrWhiteSpace(.Net framework 4.0 及更高版本支持),对于 .Net framework 3.5 或更低版本,您可以string.IsNullOrEmpty使用string.Trim

您的检查将所有条件都可能是这样的:

if (!string.IsNullOrWhiteSpace(BugCompPct.Text))
{
    int temp; 
    if(int.TryParse(BugCompPct.Text,out temp)
    {
        if(temp >= 0 && temp <= 100)
        {
            //valid number (int)
        }
        else
        {
            //invalid number (int)
        }
    }
    else
    {
        //Entered text is not a number (int)
    }
}
else
{
    //string is empty
}
于 2013-05-24T11:43:49.157 回答
1

放入文本框中的每个值都是字符串。然后,我建议您尝试解析而不是 convert.to。 (为什么?tryparse 可以更容易处理,并且如果有错误的值放入它也不会崩溃和烧毁)

只需使用 int.TryParse(txtbox1.text, out i)

您必须在此之上定义整数 i

那么您可以使用 if 语句使用 i (整数版本)来验证它。

要检查它是否只是一个整数,只需使用:

if(!int.TryParse(txtbox1.text, out i))
{
    // do work
}

那么您可以在 if 语句中使用 > < 来检查数字的大小。

于 2013-05-24T11:46:20.413 回答
1

首先检查是否TextBox为空,然后检查字符串是否为有效数字,最后检查边界。

int number = 0;

if (string.IsNullOrEmpty(this.BugCompPct.Text)
{
    //not valid
}
else if (Int32.TryParse(this.BugCompPct.Text, out number))
{
    if (number > 0 && number < 100)
    {
       //valid
    }
}
于 2013-05-24T11:46:38.890 回答
1

如果您使用的是 Windows 窗体,则应使用蒙版文本框。

于 2013-05-24T11:48:34.003 回答