Question

My project assignment requires the use of input validation using If statements. In addition, if the user leaves the Trade Allowance field blank, a default $0 should be used. My textbook is not helping me understand how these work at all, it will only show small sections of code, and it doesn't show any practical use. My overall project is working as intended, but when I try to input nonnumeric data, or leave a field blank the program crashes. It does show the message I set, but it doesn't give the user a chance to fix their error.

    '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)
Was it helpful?

Solution

To avoid users putting non numeric data into a textbox, you could avoid textbox ;) The NumericUpDown was meant for inputing numbers.

But if you need to or want to use a Textbox, you make use of TryParse instead of catching exceptions.

    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
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top