Error when trying to create the form

mEEzz

New member
Joined
Mar 12, 2013
Messages
2
Programming Experience
Beginner
Hi,

I'm fairly new to VB been using it for around a Week orso with no coding background, and i was trying to make a program, but every time i try and run the program i get the error "An error occurred creating the form. See Exception.InnerException for details. The error is: Object reference not set to an instance of an object."
Could someone please tell me whats wrong with my code and also why i'm getting this error, so in the future i can avoid it.

Thanks for your time. :ghost:

My code:

VB.NET:
Public Class Form1

    Dim Planet As String = cbPlanet.Text
    Dim d As Double = Val(txtDistance.Text)
    Dim v As Double = Val(txtVelocity.Text)
    Dim a As Double = Val(txtAngle.Text)
    Dim y As Double = Val(txtYheight.Text)

    Private Sub cmdCalculate_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdCalculate.Click

        Select Case Planet
            Case "Earth"
                earth()
        End Select

    End Sub

    Private Sub earth()

        txtGravity.Text = 9.81

        If y = 0 Then
            d = ((v ^ 2) * Math.Sin(2 * a)) / txtGravity.Text
        ElseIf y > 0 Then
            d = ((v * Math.Cos(a)) / txtGravity.Text) * ((((v ^ 2) * Math.Sin(a)) + ((v ^ 2) * (Math.Sin(a) ^ 2) + 2 * txtGravity.Text * y)) ^ (1 / 2))
        End If

    End Sub

    Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load

        txtVert.ReadOnly = True
        txtHoriz.ReadOnly = True
        txtGravity.ReadOnly = True
        txtDistance.ReadOnly = True

    End Sub
End Class
 
The issue is these lines:
VB.NET:
    Dim Planet As String = cbPlanet.Text
    Dim d As Double = Val(txtDistance.Text)
    Dim v As Double = Val(txtVelocity.Text)
    Dim a As Double = Val(txtAngle.Text)
    Dim y As Double = Val(txtYheight.Text)
All declarations are processed before the form is initialised so that means that, when that code is executed, the TextBox and ComboBox controls don't exist. The variables exist but no controls have been created and assigned to those variables so they are all Nothing, i.e. a null reference. If a control doesn't exist then you can't get its Text property.

Even if the controls did exist though, that code still wouldn't do you any good. What's the use of getting the Text of a TextBox when the form is first created, before the user has entered anything? You have to get the value of those properties when you want to use them because they will change in between. That means in the Click event handler of your Calculate button.
 
Back
Top