2010-11-02 47 views
1

我想驗證數字在Visual Basic中是十進制數。 msgBox顯示的數字有效時得到的結果。當它無效時,我沒有收到msgBox,並且程序崩潰,並顯示錯誤消息,該數字必須小於無窮大。驗證文本框中的十進制數

我試着添加另一個If Not IsNumeric(txt1.text),然後 - 但收到了相同的結果。

我哪裏出錯了?

If IsNumeric(txt1.text) Then 
    msgBox("good") 
Else 
    msgBox("not good") 
End If 
+0

該代碼應該工作。你能發佈確切的錯誤信息嗎? – David 2010-11-02 16:07:04

回答

3

嘗試使用Double.TryParseDecimal.TryParse而不是IsNumeric。

Dim result as Double = 0.0 
if Double.TryParse(txt1.text, result) then 
    ' valid entry 
else 
    ' invalid entry 
end if 
+0

謝謝,這是最容易理解的版本。 – jpavlov 2010-11-02 17:07:03

0

可以忽略文本框的按鍵事件字符,如:

Private Sub txtValue_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles txtValue.KeyPress 
     If Not Char.IsDigit(e.KeyChar) Then 
      If Not (e.KeyChar = vbBack) Then 
       e.Handled = True 
      End If 
     End If 
End Sub 

不知道哪個版本你正在使用VB,假設它是.NET

1

我剛剛到寫一個函數,限制輸入到文本框的有效十進制值,並且我想出了以下內容:

Private Sub validateDecimalTextBox(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) handles myTextBox.keyPress 
     Dim textBox As TextBox = DirectCast(sender, TextBox) 
     If Not (Char.IsDigit(e.KeyChar) Or Char.IsControl(e.KeyChar) Or (e.KeyChar = "." And textBox.Text.IndexOf(".") < 0) Or (e.KeyChar = "-" And textBox.Text.Length = 0)) Then 
      e.Handled = True 
     End If 
    End Sub 

這應該將用戶輸入限制爲十進制值,並允許負值。

如果限制用戶的輸入,然後當你從文本框中獲取的價值了,你可以更加確信它是有效的。

該解決方案是不完整的。然而,因爲這將允許用戶只需輸入「 - 」,其中將(可能)不適合你的有效輸入文本框。因此,您可以使用其他人提到的解決方案,並以合理的方式使用以下任何內容。

double.parse, 
double.tryparse 
isNumeric() 

我個人的偏好是isNumeric(),但選擇是真的取決於你。

0

您還可以使用文本框按鍵事件。即

Private Sub Textbox1_KeyPress(sender As Object, e As KeyPressEventArgs) Handles Textbox1.KeyPress 
    If (e.KeyChar < "0" Or e.KeyChar > "9") And e.KeyChar <> "." And e.KeyChar <> ControlChars.Back Then 
     e.Handled = True 
    Else 
     If e.KeyChar = "." Then 
      If Textbox1.Text.Contains(".") Then 
       Beep() 
       e.Handled = True 
      End If 
     End If 
    End If 

End Sub 

我希望這有助於。