Jesse S
Jesse S

Reputation: 81

Invalid Cast Expression?

How do I get rid of invalid cast expression from the Values in the Combobox to fit in the equation in examgrade?

I tried to resolve it by looking it up on MSDN, and the like but couldnt figure it out. I tried using Examgrade = ().ToString but that did not work.

Hope you guys can point me in the right direction. FYI this is my first real program, I successfully made this once in C# but deleted the source files, so this is Visual Basic and a hell of a lot easier to get this far.

The asterisks mark the problem line

Public Class Calculator
Dim quarter3 As Integer
Dim quarter4 As Integer
Dim desiredgrade As String
Dim examgrade As String

 Private Sub Button1_Click(ByVal sender As System.Object, _
 ByVal e As System.EventArgs) Handles Button1.Click
    quarter3 = TextBox1.Text
    quarter4 = TextBox2.Text
    desiredgrade = ComboBox1.Text
    ****examgrade = ((desiredgrade - (quarter3 * 0.4) - _
    (quarter4 * 0.4)) / 0.2)****

    If examgrade > 100 Then
        Label5.Text = examgrade + " YOLO"
    ElseIf examgrade < 0 Then
        Label5.Text = "Impossible"
    Else
        Label5.Text = examgrade
    End If
End Sub

Private Sub ComboBox1_SelectedIndexChanged(ByVal sender _
As System.Object, ByVal e As System.EventArgs) Handles _
ComboBox1.SelectedIndexChanged
    Dim A As Integer
    Dim B As Integer
    Dim C As Integer
    Dim D As Integer
    A = 90
    B = 80
    C = 70
    D = 60
    ComboBox1.EndUpdate()
End Sub
End Class

Upvotes: 2

Views: 404

Answers (2)

Tyler G
Tyler G

Reputation: 11

Unless there's a specific reason for having examgrade as a String, try the following:

Dim examgrade as Integer

examgrade = ((CInt(desiredgrade) - (quarter3 * 0.4) - _
(quarter4 * 0.4)) / 0.2)

VB will automatically convert examgrade to a String when you assign it to your label.

Upvotes: 1

Siddharth Rout
Siddharth Rout

Reputation: 149287

desiredgrade is a string

examgrade = ((Double.Parse(desiredgrade) - (quarter3 * 0.4) - _
            (quarter4 * 0.4)) / 0.2).ToString()

I am using Double. You can also use Integer if required.

examgrade = ((Integer.Parse(desiredgrade) - (quarter3 * 0.4) - _
            (quarter4 * 0.4)) / 0.2).ToString()

Upvotes: 2

Related Questions