VB.Net从字符串转换为double

时间:2010-11-18 08:27:46

标签: vb.net string textbox type-conversion

我的程序中有一个错误的错误,如果用户在文本框中没有输入时按下check(计算)按钮,程序会显示以下错误:“从字符串转换”“到'Double'类型无效“。我想解决这个问题,但我不知道如何进行转换。我在想CType但是我听到了解析的话题。我该怎么做?文本框称为mskTxtInput,按钮对象称为btnCheck,它执行所有计算和处理。

更新:这是我的代码,除了解析方法,所以希望这有点帮助!

Private Sub btnCheck_Click(ByVal sender As System.Object,ByVal e As System.EventArgs)处理btnCheck.Click         pic1.Visible = False'隐藏图片         pic1.Image = My.Resources.A         pic2.Image = My.Resources.F

    Dim value As Double
    If Double.TryParse(mskTxtInput.Text, value) = Then
        MsgBox("parsing success") ' parsing worked, so use the value in here 
    Else
        MsgBox("parsing failed") ' parsing failed, so alert the user to that fact 
    End If


    If radAdd.Checked = True Then
        totalNum = num1 + num2


    End If

    If radSub.Checked = True Then
        totalNum = num1 - num2

    End If

    If radMulti.Checked = True Then
        totalNum = num1 * num2



    End If

    If mskTxtInput.Text = totalNum Then
        lblAns.Text = ("Correct!")
        lblAns2.Text = ("Answer is " & totalNum)
        pic1.Visible = True
        wins = wins + 1
        nScore = wins



    Else
        lblAns.Text = ("Incorrect")
        lblAns2.Text = ("Answer should be " & totalNum)
        pic2.Visible = True

    End If

    attempts = attempts + 1
    If attempts = 5 Then
        MessageBox.Show("Game Finished! ", "End Of Game", _
                        MessageBoxButtons.OK, _
                        MessageBoxIcon.Exclamation)
        lblAns.Text = ("You scored " & wins & " Out of 5")
        btnSpin.Enabled = False
        pic1.Visible = False
        pic2.Visible = False
        lblAns2.Text = ""
        lblAns2.Text = "Play again?"
        btnCheck.Enabled = False
        btnNew.Enabled = True
        attempts = 0
        wins = 0
    End If


    mskTxtInput.Clear()
    mskTxtInput.Focus()


End Sub

4 个答案:

答案 0 :(得分:4)

尝试使用Double.TryParse Method (String, Double)而不是

这样的东西
Dim s As String
Dim result As Double
Dim returnValue As Boolean

returnValue = Double.TryParse(s, result)

答案 1 :(得分:3)

使用TryParse方法进行解析,以避免在解析失败时出现异常:

Dim value As Double
If Double.TryParse(mskTxtInput.Text, value) Then
  ' parsing worked, so use the value in here
Else
  ' parsing failed, so alert the user to that fact
End If

答案 2 :(得分:0)

将iVar调整为整数 dim sStr as string

SSTR = “”

ivar = val(sstr)

答案 3 :(得分:0)

使用静态方法Double.TryParse()。如果它返回true,则解析成功,您可以继续操作。如果它返回false,则解析不成功,您应该显示一条错误消息(如果需要,使用MessageBox)并中止操作。