“从字符串”到“ Double”类型的转换无效” VB

问题描述 投票:0回答:1

这里有人可以提供帮助吗?我应该怎么做?我收到此消息“从字符串”转换为“ Double”无效”,但我不知道该怎么办。这是代码。

    Dim Amount As String = TextBoxAmount.Text

    If Amount = "" Or Not IsNumeric(Amount) Then
        MsgBox("Incorect Format!", InfoOKOnly, AppTitle)
        TextBoxAmount.Focus()
        Return '- Exit Sub
    End If

    Dim DblAmount As Double = CType(Amount, Double)
    If (DblAmount < 500) Then
        MsgBox("Amount must be greater than or equal to 500", InfoOKOnly, AppTitle)
        TextBoxAmount.Focus()
        Return
    End If

    TextBoxAmount.Text = Format(DblAmount, "#,##0.  00")
End Sub

Private Sub ButtonSave_Click(sender As Object, e As EventArgs) Handles ButtonSave.Click
    If (MsgBox("Do you want to continue?", vbQuestion + vbYesNo, AppTitle) = MsgBoxResult.Yes) Then
        If TextBoxAccountNo.Text = "" Or String.IsNullOrEmpty(TextBoxAccountNo.Text) Or
           TextBoxAccountName.Text = "" Or String.IsNullOrEmpty(TextBoxAccountName.Text) Or
           TextBoxPhoneNo.Text = "" Or String.IsNullOrEmpty(TextBoxPhoneNo.Text) Or
           TextBoxAmount.Text = "" Or String.IsNullOrEmpty(TextBoxAmount.Text) Then
            '--^_^
            Return
        End If

        Dim cf As MyClassFiles1 = New MyClassFiles1()

        Dim accNo As String = TextBoxAccountNo.Text
        Dim accName As String = TextBoxAccountName.Text
        Dim PhoneNo As String = TextBoxPhoneNo.Text
        Dim Cash As Double = CDbl(TextBoxAmount.Text)

问题就在这里,在这行代码中(上面第一条)。当我在文本框(数量)中输入数字时,它说不能转换为双精度。

        Dim o As MyAccountClass1 = New MyAccountClass1(accNo, accName, PhoneNo, Cash)

        FileOpen(1, cf.GetMasterFile, OpenMode.Append)

        '-- C stand for Create New Account
        WriteLine(1, o.AccountNo, o.AccountName, o.PhoneNo, o.Amount, "Active")

        FileOpen(2, cf.GetTransactionFile, OpenMode.Append)

        WriteLine(2, o.AccountNo, CreatedDate, CreatedTime, "C", o.Amount)

        '--Close before reopening in another mode.

        FileClose(1)
        FileClose(2)

        MsgBox("The files have been saved!", InfoOKOnly, AppTitle)

        ClearTextBoxes()
    End If
End Sub

结束类

vba vb.net
1个回答
0
投票

我建议使用TryParse

    ...
    Dim Cash As Double
    If Not Double.TryParse(TextBoxAmount.Text, Cash) Then
        'do sth, show some msgbox that value in the textBox is incorrect
    End If
    ...

此外,您的支票String.IsNullOrEmpty应该替换为String.IsNullOrWhiteSpace,因为您在TextBoxAccountNo.Text = ""之前检查是否为空

还有关于代码的另一件事。您想使用OrElse而不是Or检查this question,尤其是this answer

© www.soinside.com 2019 - 2024. All rights reserved.