Tlm7
Tlm7

Reputation: 35

Getting an object reference error in VB.net

Curious as to why I'm getting this error when attempting to debug my program in VB.net

Object Reference not set to an instance of the object.

It says that I am receiving this error due to lines 4 and 5:

Public Class Form1

Dim tSize
Dim S1 As String = ComboBox1.Text
Dim S2 As String = ComboBox2.Text

Private Sub FitContents()
    tSize = TextRenderer.MeasureText(TextBox3.Text, TextBox3.Font)
    TextBox3.Width = tSize.Width + 10
    TextBox3.Height = tSize.Height
End Sub

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
    TextBox1.Text = S1
    TextBox2.Text = S2
End Sub

Private Sub TextBox3_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles TextBox3.TextChanged
    Call FitContents()
End Sub

End Class

I would be extremely grateful if somebody were to explain why I am receiving this error.

Upvotes: 3

Views: 497

Answers (1)

Joel Coehoorn
Joel Coehoorn

Reputation: 415735

Class level variables like S1 and S2 are initialized very early in the object construction process. Your visual controls, like Combobox1 and Combobox2, are not created until the InitializeComponent() method is called, which is not until almost at the end of the constructor.

Therefore, at the point when you try to set S1 to the value of Combobox1.Text, the Combobox1 object has not been created yet, and tring to reference a Null object's .Text property is going to give you that exception.

Instead, set those values at the end of your constructor, or in response to an event like Load.

You can also try building them as a property... like this:

Private Property S1() As String
    Get
        Return ComboBox1.Text
    End Get
    Set (ByVal value As String)
        ComboBox1.Text = value
    End Set
End Property

Upvotes: 4

Related Questions