I am trying to catch the System.InvalidCastException error. If I put a number into the calculator the program runs ok. If the calculate button is pressed with nothing in the text boxes I get the casting error Conversion from string "" to type 'Decimal' is not valid. I understand why I am getting the error. I don't know what to do about it. I want the program to dump null data and go back to waiting for input from the user. Thanks

Private Sub btnCalculate_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnCalculate.Click


        Dim FedTaxRate = 0.13     ' constants for taxes and work week
        Dim StateTaxRate = 0.07
        Dim StandWorkWeek = 40
        Dim GrossPay As Decimal    ' variables 
        Dim NetPay As Decimal

        If txtInHours.Text = "" Then
            MessageBox.Show("Please enter a number in the hours box", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error, MessageBoxDefaultButton.Button1)

            If txtInWage.Text = "" Then
                MessageBox.Show("Please enter a number in the wage box", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error, MessageBoxDefaultButton.Button1)

            End If
        End If

        Dim decInHours = CDec(txtInHours.Text) 'converts text boxes to numerical data
        Dim decInWage = CDec(txtInWage.Text)


        If decInHours <= StandWorkWeek Then        'calculates gross and net pay as well as taxes. Also includes overtime after 40 hours
            GrossPay = (decInHours * decInWage)

        ElseIf decInHours > StandWorkWeek Then

            GrossPay = (decInWage * StandWorkWeek) + (decInHours - StandWorkWeek) * (decInWage * 1.5)

        End If


        NetPay = GrossPay - (GrossPay * FedTaxRate) - (GrossPay * StateTaxRate)

        lblGrossPay.Text = GrossPay.ToString("c")
        lblNetPay.Text = NetPay.ToString("c")
        lblFedTax.Text = (GrossPay * FedTaxRate).ToString("c")
        lblStateTax.Text = (GrossPay * StateTaxRate).ToString("C")


    End Sub

Dani AI

Generated

Short answer: validate and parse the text fields before converting. As discovered, a direct conversion on an empty string will throw. As pointed out, check each field independently and stop the handler if any validation fails.

A practical pattern is to use Decimal.TryParse (it returns True/False and never throws) and Exit Sub to bail out early. Example helper and usage:

Private Function ParseDecimalInput(input As String, fieldName As String, ByRef result As Decimal) As Boolean
    input = If(input Is Nothing, String.Empty, input).Trim()
    If input = String.Empty Then
        MessageBox.Show("Please enter a number in the " & fieldName & " box", "Input required", MessageBoxButtons.OK, MessageBoxIcon.Warning)
        Return False
    End If

    If Not Decimal.TryParse(input, System.Globalization.NumberStyles.Number, System.Globalization.CultureInfo.CurrentCulture, result) Then
        MessageBox.Show(fieldName & " must be a valid number.", "Invalid input", MessageBoxButtons.OK, MessageBoxIcon.Warning)
        Return False
    End If

    Return True
End Function

' Usage inside the Click handler:
Dim hoursValue As Decimal
If Not ParseDecimalInput(txtInHours.Text, "hours", hoursValue) Then Exit Sub
Dim wageValue As Decimal
If Not ParseDecimalInput(txtInWage.Text, "wage", wageValue) Then Exit Sub
' safe to calculate here

Notes and tips:

  • Trim input first to avoid hidden whitespace causing a parse failure.
  • Use ErrorProvider or the control's Validating event for less intrusive validation than MessageBox.
  • Consider NumericUpDown when only numeric input is allowed (set DecimalPlaces).
  • Be mindful of culture-specific decimal separators — TryParse with CurrentCulture handles the user's locale.
  • If exceptions still appear, surround only the risky conversion with Try/Catch and log the exception, but prefer TryParse to avoid exceptions altogether.

Recommended Answers

All 2 Replies

Your code seems to present the message box saying 'please enter a value' and then continues through the rest of the function after that. It doesn't exit to await new input. Also, you've nested your if loops. txtInWage.Text = "" is only tested if txtInHours.Text = "". Meaning txtInHours needs to equal an empty string before txtInWage is checked. If txtInHours has a value entered but txtInWage doesn't you've got a problem.

ok I fixed the nested loop problem. I still have no idea how to fix the null data problem. Would I be better off using a do while loop? something like

while

textinput is not a number 

do

display error msg
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.