1

私はうまく動作するように見えるこのコードを持っています。唯一の問題は、テキストボックスにいるときにボタンをダブルクリックするか、Enterキーをダブルクリックすると、ここで例外が発生することです

"If GotxtBox.Text < 10 Then"

「無効なケースの例外が処理されませんでした」「文字列から double 型への変換は無効です」と表示されます。これを防ぐにはどうすればよいですか?

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 に答える