hi,

I am trying to validate a textbox that has a value of 1 and up so i am saying :

if (mytextbox.Text > 0)
      {
          //do something
      }

but it is not working any suggestions please bare in mind that the text has 0 as default value so i cannot say length

Narue's reply from the C++ forum is still applicable.
i.e. the text property returns a string so you need to convert it to an integer before the compare.

In your case I would use a NumericUpDown control. No more need for any validation just set it's Minimum and Maximum properties to the values you need. You cannot even type letters etc. in a NumericUpDown.

Edited 6 Years Ago by ddanbe: n/a

but even if i convert it still the if statement fails i have done convert.ToInt32(mytextbox.Text) ...

Works just fine for me:

if (Convert.ToInt32(textBox1.Text) > 0)
{ MessageBox.Show("Do something next");
}

Ionut

What are you using to indicate that the datum needs validation (e.g., button, pressing enter, etc.)? I allowed enter in the textbox, checked for the key down and it worked with the convert method.

EDIT: That was a tie lol

Edited 6 Years Ago by jonsca: n/a

i would suggest that you first calculate the length of textbox, and then check the length of that textbox .like: length>0

please bare in mind that the text has 0 as default value so i cannot say length

That was part of the OP's requirement...

Edited 6 Years Ago by jonsca: n/a

That was part of the OP's requirement...

Just because the default value is zero it doesn't prevent checking against length. A value of '0' in the box has a length of 1. I can't see the point of checking length anyway. It could be invalid if the length is 0 and if it's greater than zero.
So, to validate the box you must convert to integer as stated earlier. The box may be empty and the conversion will fail so first check the conversion succeeds:

int myInt;
if (int.TryParse(textBox1.Text, out myInt) && (myInt > 0))
{
     // Input is valid
}

It would certainly help if you gave an example of an input value that was failing.

This article has been dead for over six months. Start a new discussion instead.