我什么时候可以访问表单的成员?

时间:2012-12-21 17:11:21

标签: vb.net winforms events controls lifecycle

起初我试过这个:

Public Class frmWait

Public Sub New(ByVal uWindowText As String, ByVal uInfoText As String)

    Me.Text = uWindowText
    Me.lblInfoText.Text = uInfoText

End Sub

End Class

但是当我发起这样的表格时

            Dim wait As New frmWait("blah", "blah")
            wait.Show()

...它在这一行告诉我“NullReference Exception”:

Me.lblInfoText.Text = uInfoText

设置表单的文本工作正常。 好吧,当我尝试设置文本时,我认为标签还没有创建。

然后我尝试了以下内容。我将文本存储在变量中,并希望在创建控件时设置它们。我认为“Form_Load”是一个很好的事件:

Public Class frmWait

Private m_sWindowText As String = ""
Private m_sInfoText As String = ""


Public Sub New(ByVal uWindowText As String, ByVal uInfoText As String)

    'we can not set the texts right away because lblInfo does not seem to exist yet

    m_sWindowText = uWindowText
    m_sInfoText = uInfoText

End Sub

Private Sub frmWait_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load

    Me.Text = m_sWindowText
    Me.lblInfoText.Text = m_sInfoText

End Sub

End Class

但它也犯了同样的错误。 Ehhhhh,我可以直接设置控件的文本吗? 我是否犯了任何初学者的错误?

2 个答案:

答案 0 :(得分:4)

不要删除设计师所做的事情:)它试图帮助你。当您创建

Public Sub New(...)

在表单上,​​它会自动输入:

Public Sub New()

    ' This call is required by the designer.
    InitializeComponent()

    ' Add any initialization after the InitializeComponent() call.

End Sub

需要InitializeComponent()才能让表单准备就绪。

答案 1 :(得分:2)

看起来你错过了InitializeComponents调用:

Public Sub New(ByVal uWindowText As String, ByVal uInfoText As String)
  InitializeComponents()

  m_sWindowText = uWindowText
  m_sInfoText = uInfoText
End Sub

方法调用加载使用设计器创建的所有控件。没有那个电话,你的表格就是空的。