2013-10-28 44 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

很简单,非常感谢! :) –