vb.net 使用 TryParse 方法将字符串“”转换为“Double”类型无效

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18927914/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-17 15:09:54  来源:igfitidea点击:

Conversion from string "" to type 'Double' is not valid using TryParse Method

vb.nettryparse

提问by OneFineDay

I have a simple addition program in VB.Net and I am attempting to test if the textbox is only taking in a number and not any letters. I need to use the TryParse method, and I cannot figure out wny I am still receiving this error. Pls Help

我在 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

回答by OneFineDay

This is how you use the TryParse:

这是您使用 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

End the code block if text is empty:

如果文本为空,则结束代码块:

If String.IsNullOrWhiteSpace(numberOneInput.Text) Then 
   MessageBox.Show("Value is incorrect format")
   Exit Sub
End If