2013-10-28 41 views
0

我的項目分配需要使用If語句進行輸入驗證。另外,如果用戶將交易限額字段留空,則應該使用默認的$ 0。我的教科書並沒有幫助我理解這些工作是如何工作的,它只會顯示一小段代碼,並沒有顯示任何實際用途。我的整體項目按預期工作,但是當我嘗試輸入非數字數據或將字段留空時,程序崩潰。它確實顯示了我設置的消息,但它沒有給用戶修復錯誤的機會。使用If語句的輸入驗證

'Having a problem here... 
    AccessoriesTextBox.Text = AccessoriesAndFinish.ToString() 

    If CarSalesTextBox.Text <> " " Then 
     Try 
      CarSalesPrice = Decimal.Parse(CarSalesTextBox.Text) 
     Catch CarSalesException As FormatException 
      MessageBox.Show("Nonnumeric data entered for Car Sales Price.", "Data Entry Error", 
          MessageBoxButtons.OK) 
      CarSalesTextBox.Focus() 
     End Try 
    ElseIf CarSalesTextBox.Text <> "" Then 
     MessageBox.Show("Enter the Car Sales Price.", "Data Entry Error", 
         MessageBoxButtons.OK) 
     CarSalesTextBox.Focus() 
    End If 

    'Also having a problem here... 
    If TradeTextBox.Text <> "" Then 
     TradeAllowance = 0D 
     If TradeTextBox.Text <> " " Then 
      TradeAllowance = 0D 
     End If 
    End If 

    'Convert Trade Allowance to Decimal 
    TradeAllowance = Decimal.Parse(TradeTextBox.Text) 
+0

你的具體問題是什麼? – admdrew

+0

我需要弄清楚如何使用If語句處理輸入錯誤。截至目前,如果任何字段留空或者輸入非數字數據,程序崩潰。我不知道如何將其轉換成代碼。 –

+0

正如您之前的問題之一的答案,您應該使用'TryParse'而不是'Parse'。 – admdrew

回答

0

爲了避免用戶把非數字數據轉換爲文本框,你可避免文本框;) 的的NumericUpDown是爲那些輸入查詢號碼。

但是,如果您需要或想要使用文本框,則可以使用TryParse而不是捕捉異常。

Dim value As Decimal ' to hold the numeric value we need later 

    If tb.Text = String.Empty Then 
     ' either throw error and exit method or use default value 
    ElseIf Not Decimal.TryParse(tb.Text, value) Then 
     ' not a decimal, inform user and exit sub 
    End If 
    ' value contains something meaningfull at this point 
+0

很簡單,非常感謝! :) –