0

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

8
Contributors
9
Replies
24
Views
9 Years
Discussion Span
Last Post by Michael27
0

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");
}

0

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 by Nick Evan: Added code-tags

1

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.

0
  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 by Dani: Formatting fixed

0

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.

0

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 topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.