【发布时间】:2011-05-11 21:40:55
【问题描述】:
我的程序中有一个严重的错误,如果用户在文本框中没有输入时按下检查(计算)按钮,程序会显示此错误:“从字符串转换”到类型“双”无效。”我想解决这个问题,但我不确定如何进行转换。我在想可能是 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
【问题讨论】:
-
请分享一些出现此问题的代码。
-
这与您的问题没有直接关系,但您似乎没有使用
Option Strict。我建议你打开它:编译器会生成关于危险代码的警告,从长远来看这会节省你的时间。
标签: vb.net string textbox type-conversion