Reputation: 930
I am checking a text box for the following
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
Upvotes: 0
Views: 18605
Reputation: 223267
What could I put as the if conditional to check for a string other than an integer?
Use int.TryParse
method to see if the parsing is succesfull.
For empty string use string.IsNullOrWhiteSpace
(supported on .Net framework 4.0 and later), For .Net framework 3.5 or lower you can use string.IsNullOrEmpty
with string.Trim
Your check will all the conditions could be like:
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
}
Upvotes: 3
Reputation: 995
every value put into a textbox is as string. I would then advise you to tryparse rather than convert.to. (Why? tryparse can be handled much easier and won't crash and burn if there are bad values put into it)
just use int.TryParse(txtbox1.text, out i)
You must define integer i above this
then you can use if statements using i (the integer version) to validate it.
To check if its an integer only just use:
if(!int.TryParse(txtbox1.text, out i))
{
// do work
}
then you can use > < in if statements to check how big the number is.
Upvotes: 1
Reputation: 17600
First check if TextBox
is empty, then if string is valid number and last check boundaries.
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
}
}
Upvotes: 1