Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations bkrike on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Unhandled Exception Error

Status
Not open for further replies.

tekrobg

Programmer
Oct 12, 2004
42
US
I have a text box that the user enters a number in decimal form. I set the KeyPress event to only allow numbers, one decimal point, and the backspace key. The TextChanged event manipulates the number the user enters, then outputs it to a label. It works great; however, if the user enters any numbers, then presses backspace all the way back to the beginning of the box, an unhandled exception error occurs. The other situation that this same error occurs is when the user enters some numbers, then left arrows back to the beginning of the box, and then presses the delete key. When the last number gets deleted, the error occurs. Please help. Here's the error:

error:
An unhandled exception of type 'System.FormatException' occurred in mscorlib.dll

Additional information: Input string was not in a correct format.
/error

Here's my code:

vb:
Private Sub TextBox5_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles TextBox5.TextChanged
Dim n As Double = Double.Parse(TextBox5.Text)
Dim Lbs As Double = Math.Floor(n)
Dim nLbs As Double = n - Lbs
Dim nLbs16 As Double = nLbs * 16
Dim Oz As Double = Math.Ceiling(nLbs16)
Label6.Text = "= " & Lbs & " lbs, " & Oz & " oz"
End Sub

Private Sub Label6_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Label6.Click

End Sub

Private Sub TextBox5_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles TextBox5.KeyPress
If Not (e.KeyChar >= "0"c AndAlso e.KeyChar <= "9") AndAlso e.KeyChar <> Convert.ToChar(8) AndAlso e.KeyChar <> "."c Then
e.Handled = True
Else
If e.KeyChar = "." And TextBox5.Text.IndexOf(".") <> -1 Then
e.Handled = True
End If
End If
End Sub
/vb

Thanks for any help.
 
I think you get the error on the double.parse if you pass it an empty value so if you do this it should be better

Code:
if textbox5.text.length = 0 then
  Dim n As Double = Double.Parse(TextBox5.Text)
  Dim Lbs As Double = Math.Floor(n)
  Dim nLbs As Double = n - Lbs
  Dim nLbs16 As Double = nLbs * 16
  Dim Oz As Double = Math.Ceiling(nLbs16)
  Label6.Text = "=  " & Lbs & " lbs, " & Oz & " oz"
end if


Christiaan Baes
Belgium

If you want to get an answer read this FAQ faq796-2540
There's no such thing as a winnable war - Sting
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top