在VB.net中获取对象引用错误

时间:2012-12-21 03:04:03

标签: vb.net

想知道为什么我在尝试在VB.net中调试程序时出现此错误

Object Reference not set to an instance of the object.

它说由于第4行和第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

如果有人要解释我收到此错误的原因,我将非常感激。

1 个答案:

答案 0 :(得分:4)

类对象级别变量(如S1和S2)在对象构建过程中很早就被初始化了。您的可视控件(如Combobox1和Combobox2)在调用InitializeComponent()方法之前不会创建,直到几乎在构造函数结束时才会创建。

因此,当您尝试将S1设置为Combobox1.Text的值时,尚未创建Combobox1对象,并且引用Null对象的.Text属性将为您提供该异常。< / p>

相反,请在构造函数的末尾设置这些值,或者响应Load之类的事件。

您也可以尝试将它们构建为属性......就像这样:

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