我正在检查以下
的文本框代码 -
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
我可以将if作为if条件来检查除整数之外的字符串吗? 我只希望输入是整数而不是其他
谢谢
答案 0 :(得分:3)
我可以将if作为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
}
答案 1 :(得分:1)
放入文本框的每个值都是字符串。然后我建议你tryparse而不是convert.to。 (为什么?tryparse可以更轻松地处理,并且如果存在错误值,则不会崩溃和刻录)
只需使用int.TryParse(txtbox1.text,out i)
您必须在此
之上定义整数i然后你可以使用if语句(整数版本)来验证它。
要检查它的整数是否只使用:
if(!int.TryParse(txtbox1.text, out i))
{
// do work
}
然后你可以使用&gt; &LT;在if语句中检查数字的大小。
答案 2 :(得分: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
}
}
答案 3 :(得分:1)
如果你在Windows窗体上,你应该使用蒙面文本框。