2012-10-01 25 views
0

我需要檢查兩個文本框textbox_price和textbox_quantity是否包含數值或根本沒有值,如果發出特定的錯誤消息。 textbox_item只允許使用非數字字符。目前使用下面的OR連接並且它起作用,但是我想知道這是否有效且很好。正如你所看到的,支票很長且很難閱讀。幫助讚賞。在邏輯這是很好的VB.Net編碼語法嗎?

If textbox_item.Text = "" Or textbox_price.Text = "" Or textbox_quantity.Text = "" Or   IsNumeric(textbox_price.Text) = False Or IsNumeric(textbox_quantity.Text) = False Or IsNumeric(textbox_item.Text) = True Then 
     MsgBox("Please fill out every textbox with valid data", MsgBoxStyle.Information, "Invalid entry") 
     textbox_price.Text = "" 
     textbox_item.Text = "" 
     textbox_quantity.Text = "" 
     Exit Sub 
    End If 
+2

爲什麼要刪除他們已經輸入的任何信息,僅僅是因爲他們還沒有輸入*全部*呢? –

+1

如果它是WinForms,則有一個內置的驗證系統:http://www.sellsbrothers.com/writing/winformsdatavalidation.htm – jgauffin

+0

有一個WPF驗證系統。 – Jesse

回答

2

我寧願看到一個長If..Then..ElseIf鏈,所以錯誤消息可以是具體的問題。

If textbox_Item.Text = "" Then 
    msgbox(errmsg1) 
Elseif Not IsNumberic(textbox_Item.Text) Then 
    msgbox(errmsg2) 
Elseif .... 
+0

但是如果你把它作爲一個長IF,就像泰勒說的那樣使用ORELSE。 – Bill

+0

'Elseif'聞起來,國際海事組織,它像嵌套,但只是精神的眼睛。 – Jodrell

+0

謝謝你。 – mmenschig

2

尋找只爲If...Then聲明(而不是要執行的代碼),我會把它改成這樣:

If textbox_item.Text = "" OrElse textbox_price.Text = "" OrElse textbox_quantity.Text = "" OrElse _ 
    IsNumeric(textbox_price.Text) = False OrElse IsNumeric(textbox_quantity.Text) = False OrElse IsNumeric(textbox_item.Text) = True Then 
    'Code to execute goes here 
End If 

基本上,每個Or更改爲OrElse案件。這樣,一旦滿足其中一個條件,其他條件就不會被檢查。

下面是一個簡短的文章中VB .NET解釋OrElse

MSDN - OrElse Operator

0

您可能想要檢查IsNumeric的實現在底下做了什麼。我也懷疑你在If塊之後做了什麼。如果您在消費後檢查的價值計劃,它可能是最好只使用Decimal.TryParse(或您要使用的數字過的TryParse)和else子句中發送的驗證提示:

Dim price As Decimal 
Dim quantity As Integer 
Dim item as As Double 

If Decimal.TryParse(textbox_price.text, price) 
    AndAlso Integer.TryParse(textbox_quantity.Text, quantity) 
    AndAlso Double.TryParse(textbox_item.Text, item) Then 
    '' Do something with the values 
Else 
    '' Send validation prompt 
End If 

這個選項的優點是你不需要兩次解析這個值(IsNumeric和TryParse)。我記得,IsNumeric試圖解析,但只是拋出結果。如果您想要結果,請使用TryParse。 TryParse也處理空字符串和空字符串,所以你自己也不需要明確地測試這些測試。