J.Mead
J.Mead

Reputation: 13

InvalidCastException .Net

Screenshot of Error Message

Dim Total As Decimal
Dim Price(1, 1) As Decimal
Price(0, 0) = TxtHoursGFX.Text
Price(0, 1) = TxtHoursWeb.Text
Price(1, 0) = TxtHoursGame.Text
Price(1, 1) = TxtHoursVideo.Text

Total = Price(0, 0) + Price(0, 1) + Price(1, 0) + Price(1, 1) + 25

LboxTotal.Items.Add(Price(0, 0) * 25)
LboxTotal.Items.Add(Price(0, 1) * 30)
LboxTotal.Items.Add(Price(1, 0) * 35)
LboxTotal.Items.Add(Price(1, 1) * 27)
LboxTotal.Items.Add(Total)

If TxtHoursGFX.Text = "" Then
    MessageBox.Show("Please Enter Value")
ElseIf TxtHoursWeb.Text = "" Then
    MessageBox.Show("Please Enter Value")
ElseIf TxtHoursGame.Text = "" Then
    MessageBox.Show("Please Enter Value")
ElseIf TxtHoursVideo.Text = "" Then
    MessageBox.Show("Please Enter Value")
End If

When i try empty error handlers with Integer data types they break everytime, i feel my college tutor hasn't explained this properly how do i fix this

Upvotes: 0

Views: 68

Answers (1)

Nathan Champion
Nathan Champion

Reputation: 1322

You need to validate/convert your string to decimal. You could do something like this:

    'You'll probably want to clear the old items out every time you run whatever it is to calculate the total.
    LboxTotal.Items.Clear()

    Dim Total As Decimal
    Dim Price(1, 1) As Decimal

    Dim GFX, Web, Game, Video As Decimal

    'Parse the decimals from the string in each textbox.
    Decimal.TryParse(TxtHoursGFX.Text, GFX)
    Decimal.TryParse(TxtHoursWeb.Text, Web)
    Decimal.TryParse(TxtHoursGame.Text, Game)
    Decimal.TryParse(TxtHoursVideo.Text, Video)

    Price(0, 0) = GFX
    Price(0, 1) = Web
    Price(1, 0) = Game
    Price(1, 1) = Video


    Total = Price(0, 0) + Price(0, 1) + Price(1, 0) + Price(1, 1) + 25

    LboxTotal.Items.Add(Price(0, 0) * 25)
    LboxTotal.Items.Add(Price(0, 1) * 30)
    LboxTotal.Items.Add(Price(1, 0) * 35)
    LboxTotal.Items.Add(Price(1, 1) * 27)
    LboxTotal.Items.Add(Total)

Upvotes: 0

Related Questions