2013-07-02 49 views
0

我使用下面的代碼錯誤檢查用戶輸入的文本框:從遞歸調用防止文本框TextChanged

Private Sub txtDeadLoadFactor_TextChanged(sender As Object, e As EventArgs) Handles txtDeadLoadFactor.TextChanged 
     Dim invalidEntry As Boolean 
     If IsNumeric(txtDeadLoadFactor.Text) And Not txtDeadLoadFactor.Text = vbNullString Then 
      If Not txtDeadLoadFactor.Text > 0 Then 
       invalidEntry = True 
      End If 
     Else 
      invalidEntry = True 
     End If 
     If invalidEntry Then 
      MsgBox("Please only enter numeric data greater than 0 in all fields!", MsgBoxStyle.Critical, "Invalid Input!") 
      txtDeadLoadFactor.Text = vbNullString 
      invalidEntry = False 
     Else 
      gDeadLoadFactor = txtDeadLoadFactor.Text 
     End If 
    End Sub 

消息框兩次彈出的輸入無效。這是由於將textbox.text設置爲空字符串。我不知道如何防止這種情況發生,如果有人可以幫助清理這個混亂的代碼,它將不勝感激。

謝謝!

回答

1

如果文本等於vbNullString,則快速修復將離開Sub。把這一行在小組的開頭:

If txtDeadLoadFactor.Text = vbNullString then Exit Sub 

鑑於用戶可以手動清空垃圾箱,它會更好,如果彈出未驗證空字段。

編輯:這個重構的代碼可以幫助你:

If txtDeadLoadFactor.Text = vbNullString then Exit Sub 
If Not(IsNumeric(txtDeadLoadFactor.Text)) OrElse txtDeadLoadFactor.Text <= 0 then 
    MsgBox("Please only enter numeric data greater than 0 in all fields!", MsgBoxStyle.Critical, "Invalid Input!") 
    txtDeadLoadFactor.Text = vbNullString 
    Exit Sub 
End If 

gDeadLoadFactor = txtDeadLoadFactor.Text 
+0

我不知道爲什麼我沒有這樣做。過了漫長的一天。謝謝。 – kmaz13

0

你爲什麼文本無論如何設置爲空白?只要將文本保留在錯誤消息框中,用戶就知道哪些輸入不被允許,並且如果他們再次嘗試輸入就會得到相同的結果(即一致性,而如果您爲它們更改輸入,則它們會得到當他們再次點擊提交時出現不同的錯誤)。只是我的兩分錢。