2013-09-21 38 views
-1

我得到運行時錯誤,當我在輸入框從ISNUMERIC得到錯誤()VB.NET

Dim amount As String 
     amount = InputBox("Enter the amount of people you want to participtate", "System Message") 
     If amount < 0 Or Not (IsNumeric(amount)) Then 
      MsgBox("Please enter positive number of people", vbExclamation, "System Message") 
     End If 
+0

'如果金額<0'語句發生錯誤.. – matzone

+0

請將Option Strict On放在代碼文件的頂部,或者在項目屬性中打開它。 –

回答

2

比較字符串到數字輸入字母是相當危險的,你的臉炸燬了。你可以使它工作,但你必須小心謹慎,確保你永遠不會試圖比較一個不能轉換爲數字的字符串。這需要使用另一家運營商:

If Not IsNumeric(amount) OrElse amount < 0 Then 
     MsgBox("Please enter positive number of people", vbExclamation, "System Message") 
    End If 

注意改變順序和使用OrElse運算的,或短路的版本。如果左側已經爲True,它不會評估右側表達式。

以.NET爲中心的方法是使用Integer.TryParse()將字符串轉換爲數字。

1

爲了避免錯誤,你可以把它像這樣..

If IsNumeric(amount) Then 
    If value(amount) > 0 Then 
    'codes here 
    Else  
    MsgBox("Please enter positive number of people", vbExclamation, "System Message") 
    End If 
Else 
    MsgBox("Please enter a number of people", vbExclamation, "System Message") 
End If 
0

所以我一直在尋找驗證一個文本框,首先我想確保它不是空的,並確保它是一個號碼。我絕不是專家,但我會把我寫的代碼驗證用戶輸入。我把它放在一個函數中,因爲我有很多用戶必須輸入的文本字段。

Class MainWindow 
Private Sub Button_Click(sender As Object, e As RoutedEventArgs) 
    tb2.Text = tbCheck(tb1) 
End Sub 

Private Function tbCheck(ByRef tb As TextBox) As Boolean 
    tbCheck = tb.Text.Length > 0 
    Try 
     tbCheck = (tb.Text/1) > 0 
    Catch ex As Exception 
     tbCheck = False 
    End Try 
    Return tbCheck 
End Function 

末級

這僅僅是一個簡單的程序,我寫檢查,如果代碼工作,因爲我所希望的。 希望這可以幫助某人,或者至少告訴我是否有什麼我不見了。