2013-10-02 49 views
1

我有這個代碼似乎工作得很好。唯一的問題是,如果我在文本框中,然後雙擊該按鈕或雙擊回車鍵我來到這裏的例外如何創建一個數組並放入列表框

「如果GotxtBox.Text < 10然後」

提示「無效的情況下,異常未被擴大「 」從字符串到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 
+3

您的標題似乎不符合問題。 – LarsTech

回答

0

文本框包含文本,「10」與值10不同。您需要在比較之前轉換文本。看看Integer.Tryparse和/或Convert.ToInt32

你以後會用Val做一些事情,但是也應該改成TryParse。 NET Val與VB6 Val不同。

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 
+0

我應該改變這個,然後單獨留下Dim number As Integer = Val(GotxtBox.Text)'get number 'add the number to the end of the numberListBox GoLstBox.Items.Add(number –

+0

you can if if you do not plan on在解析過程中處理任何錯誤..你可以只用IF來代替 –

+0

會像try try異常 –

相關問題