使用If语句进行输入验证

时间:2013-10-28 20:02:00

标签: vb.net validation messagebox

我的项目分配需要使用If语句进行输入验证。此外,如果用户将交易限额字段留空,则应使用默认的$ 0。我的教科书并没有帮助我理解它们是如何工作的,它只会显示一小部分代码,并没有显示任何实际用途。我的整个项目按预期工作,但是当我尝试输入非数字数据,或者将字段留空时程序崩溃。它确实显示了我设置的消息,但它没有给用户提供修复错误的机会。

    '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)

1 个答案:

答案 0 :(得分: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
相关问题