我在VB.Net中有一个简单的添加程序,我试图测试文本框是否仅包含数字而不是任何字母。我需要使用TryParse方法,我无法弄清楚,我仍然收到此错误。请帮助
Public Class perrySolutionForm
Dim numberOne As Double
Dim numberTwo As Double
Public Function sum(ByRef numberOne As Double, ByRef numberTwo As Double)
sum = Val(numberOne) + Val(numberTwo)
End Function
Public Function difference(ByRef numberOne As Double, numberTwo As Double)
difference = Val(numberOne) - Val(numberTwo)
End Function
Private Sub sumButton_Click(sender As Object, e As EventArgs) Handles sumButton.Click
If numberOneInput.Text = "" Then
MessageBox.Show("Both fields must be filled out.")
If Double.TryParse(numberOneInput.Text, numberOne) Then
MessageBox.Show("Success")
'numberOne has a Double value
Else
MessageBox.Show("Failure")
'numberOne = Nothing
End If
Else
outputLabel.Text = sum(numberOne, numberTwo)
End If
End Sub
Private Sub numberOneInput_TextChanged(sender As Object, e As EventArgs) Handles numberOneInput.TextChanged
numberOne = numberOneInput.Text
End Sub
Private Sub numberTwoInput_TextChanged(sender As Object, e As EventArgs) Handles numberTwoInput.TextChanged
numberTwo = numberTwoInput.Text
End Sub
答案 0 :(得分:1)
这就是你使用TryParse的方法:
If Double.TryParse(numberOneInput.Text, numberOne) Then
'code for a success
'numberOne has a Double value
Else
'code for a failure
'numberOne = Nothing
End If
如果文本为空,则结束代码块:
If String.IsNullOrWhiteSpace(numberOneInput.Text) Then
MessageBox.Show("Value is incorrect format")
Exit Sub
End If