Try/Catch block for negative values


New member
Jan 21, 2005
Programming Experience
Hi all I'm new to, and need a little help writing a try/catch block. I'm trying to catch any negative number entered into a text field called txtAmount.Text. If the number entered is negative a meesage box shows indicating a positive number needs entered.

Catch Err As Exception When (CInt(txtAmount.Text)) < 0
MessageBox.Show("Transaction Amount must be a positive number.", "Checkbook")
End Try

That's my code so far. What am I doing wrong? Instead of using the actual field, do I need to store the number that was entered in a temp variable first? Examples always appreciated.

Thanks for your help!
Don't use a try catch, that's more for program errors. Use an IF statment.
if CInt(txtAmount.Text)) < 0 THEN
MessageBox.Show("Transaction Amount must be a positive number.", "Checkbook")

You could wrap this if statment in a try catch incase the user enters text which would cause an error.

Hope that helps

Thanks for clarifying that for me. I appreciate it.

I redid that protion and I now receive an error message when a negative value it input, however once I hit ok on the message box, the value I entered is then being put into the label I have to display it. What I would like to happen is when a message box appears alerting the user that an error occured, whatever was in the textbox should go away, and not be put into the label.

Please see attached print screen for clarification. You will see the error appears, but the negative value is still displaying.


  • Error.doc
    41.5 KB · Views: 36
IF IsNumeric(txtAmount.text) = true and Convert.ToInt32(txtAmount.Text) >= 0 THEN
 'rest of code from procedure
   MessageBox.Show("Transaction Amount must be a positive number.", "Checkbook")
As always in VB.NET there are many ways to accomplish this.

Do you want the messagebox display after the value is entered and the user moves the focus to another control or when the user presses the 'Calculate' button or some other time?
If you want to display the message when the focus changes, handle the validating event and set the CancelEventArgs.Cancel property to True. That will send the focus back to the textbox, but the entered text will remain. You could then select all the text to show the user that the text needs to be changed.
If you handle the keypress event for the textbox, you can make it so the user can not enter a minus sign in the textbox by setting the KeyPressEventArgs.Handled property to True.
See this thread for a way to allow only numeric values in the textbox: How to restrict TextBox?

Latest posts