1

我有这段代码,它似乎工作得很好。唯一的问题是,如果我在文本框中,然后双击按钮或双击回车键,我会在这里遇到异常

“如果 GotxtBox.Text < 10 那么”

它说“无效的案例异常未处理”“从字符串到双精度类型的转换无效”如何阻止这种情况发生?

Private Sub GoBtn_Click(sender As Object, e As EventArgs) Handles GoBtn.Click

    If GotxtBox.Text < 10 Then
        MessageBox.Show("Number can not be less than 10")
        GotxtBox.Clear()
        Return
    End If
    If GotxtBox.Text > 100 Then
        MessageBox.Show("Number can not be greater than 100")
        GotxtBox.Clear()
        Return
    End If

    Dim number As Integer = Val(GotxtBox.Text) ' get number
    ' add the number to the end of the numberListBox
    GoLstBox.Items.Add(number)

    If GoLstBox.Items.Count = 20 Then
        GoBtn.Enabled = False
        MessageBox.Show("Exactly Twenty Numbers Must Be Entered")

    End If
    GotxtBox.Clear()
    GotxtBox.Focus()


End Sub
4

2 回答 2

0

文本框包含文本,“10”与值10不一样。您需要在比较之前对文本进行转换。查看Integer.Tryparse和/或Convert.ToInt32

你稍后会用 . 做类似的事情Val,但也应该改为TryParse. NET Val 与 VB6 Val 不同。

于 2013-10-02T23:10:25.600 回答
0
Dim text As String = GotxtBox.Text 
Dim value As Double

If Double.TryParse(text, value) Then
    If value < 10 Then
        MessageBox.Show("Number can not be less than 10")
        GotxtBox.Clear()
        Return
    End If

    If value > 100 Then
        MessageBox.Show("Number can not be greater than 100")
        GotxtBox.Clear()
        Return
    End If
Else
   'error, cannot convert
    GotxtBox.Clear()
    Return
End If
于 2013-10-02T23:14:58.213 回答