Hi,

I want to validate the text in a textbox. Actually i am trying to enter to amount in the textbox. If other than integer is entered in the textbox , it should say " please enter integer value ". Can somebody pls tell me how to do this. ( With out using try catch block)

Thanks in advance

Use the Validated or Validating events of your textbox.
Something like:
private void Mytextbox_Validating(object sender,CancelEventAgrs e)
{
//check for int
//if not int:
// e.Cancel = true;
// MessageBox.Show("You need to enter an integer");
}

This should work!!!

if (myTextBox.Text != "")
{
     try
      {
             declared variable = int.parse(myTextBox.Text);
       }
      catch 
       {
           MessageBox.Show("Invalid Entry, Must be Numeric", "Error");
       }
      else
      {
          MessageBox.Show("Nothing entered in myTextBox", "Error");
       }
}

Edited 6 Years Ago by Nick Evan: Added code-tags

or you could use the numericupdown control :)
The code here is worth checking for the future if you need to validate string entries, but for numeric values the NumericUpDown control is much better. You can type directly into it if you dont want to use the arrows, you can set a maximum and minimum value.

  private void textBox1_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyValue > 58 || e.KeyValue < 49)
            {
                MessageBox.Show("Please Enter Number Only","Error");
                textBox1.Text = "";
                textBox1.Focus();
            }
        }

Edited 3 Years Ago by Dani: Formatting fixed

I guess it can even be done in assembler, but I would not even think about it of doing it!
Learn C# or C++ or whatever in a .NET environment. We live in the 21 century.

I agree with Ryshad, why use textbox that is ment for string when there is perfectly good control(numericUpDown) that is ment for integers.

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