Visual Basic无法显示文本框信息?

时间:2015-10-02 00:54:54

标签: visual-studio

我正在研究一个vb程序,我遇到了错误(呃)。我试图在消息框中显示用户输入(文本框)的内容,但是它抛出了一个`System.InvalidCastException'。这是我的代码:

Private Sub ThirteenButton1_Click(sender As Object, e As EventArgs) Handles ThirteenButton1.Click
    ' withdrawBtn
    If IsNumeric(withdrawTxtBox.Text) Then
        If Val(withdrawTxtBox.Text) > Val(My.Settings.accountBalanceBA) Then
            MessageBox.Show("Error: You can not withdraw " + withdrawTxtBox.Text + ", you only have " + My.Settings.accountBalanceBA.ToString + ".")
        ElseIf Val(withdrawTxtBox.Text) < Val(My.Settings.accountBalanceBA) Then
            MessageBox.Show("Successfully withdrawn $" + Val(withdrawTxtBox.Text) + ". Your remaining balance is $" + Val(withdrawTxtBox.Text) - My.Settings.accountBalanceBA.ToString)
        End If
    End If
End Sub

输入数字&gt;帐户balanceBA将无错误地工作,但一旦我输入一个数字&lt;平衡,它会引发错误。

非常感谢任何帮助。

2 个答案:

答案 0 :(得分:2)

该行

   MessageBox.Show("Successfully withdrawn $" + Val(withdrawTxtBox.Text) + ". Your remaining balance is $" + Val(withdrawTxtBox.Text) - My.Settings.accountBalanceBA.ToString)

特别是

Val(withdrawTxtBox.Text) - My.Settings.accountBalanceBA.ToString

正试图从数字中减去一个字符串。使用括号来获得正确的操作顺序。

(Val(withdrawTxtBox.Text) - My.Settings.accountBalanceBA).ToString

答案 1 :(得分:1)

一点建议..在执行连接时,避免使用加号(+),特别是当你有数学条件连接字符串时。你可以使用“&amp;”而不是连接。

将“加号”替换为“&amp;”最佳实践。

要更正您的代码..您可以在关闭括号后移除.ToString或将.ToString放在减法之后。 ).ToString您必须小心使用括号以避免意外结果,否则最糟糕的情况会遇到错误。

    MessageBox.Show("Successfully withdrawn $" & Val(withdrawTxtBox.Text) & ". Your remaining balance is $" & Val(withdrawTxtBox.Text) - My.Settings.accountBalanceBA)

    MessageBox.Show("Successfully withdrawn $" & Val(withdrawTxtBox.Text) & ". Your remaining balance is $" & (Val(withdrawTxtBox.Text) - My.Settings.accountBalanceBA).ToString