尝试分配标签文本时出现NullReferenceException

时间:2014-02-14 17:58:21

标签: vb.net label

我尝试调试

时收到以下异常
An unhandled exception of type 'System.NullReferenceException' occurred in HomeWork Helper.exe

Additional information: Object reference not set to an instance of an object.

它来自AddControl表单加载事件

中的这行代码
lblDescription.Text = "This Window is designed to set reminders for you for " & TypeAssign & "."

以下是模块宣言

Public TypeAssign As String

在表单打开之前已在此处指定变量TypeAssign

TypeAssign = "Tests"
frmControls.ShowDialog()

1 个答案:

答案 0 :(得分:1)

如果您在表单构造函数中编写该代码,请记住在调用InitializeComponent之后将其放入,否则将声明控件lblDescription但它尚未初始化,因此使用Text属性会导致NullReferenceException。 / p>

Public Class AddControl

     Public Sub New()
         InitializeComponent()
         lblDescription.Text = "This Window is designed to set reminders for you for " & _
                                TypeAssign 
     End Sub

当然,如果在AddControl类中看不到TypeAssign,这将不起作用。在这种情况下,简单的解决方案是通过新版本的Form构造函数

传递变量
Public Class AddControl

     Public Sub New(typeAssign as string)
         InitializeComponent()
         lblDescription.Text = "This Window is designed to set reminders for you for " & _
                                typeAssign 
     End Sub

通过

调用第二个版本
TypeAssign = "Tests"
AddControl frmControls = new AddControl(TypeAssign)
frmControls.ShowDialog()
frmControls.ShowDialog()