VB调试错误

时间:2014-02-19 18:08:49

标签: vb.net visual-studio

当我在visual basic中调试我的项目时,收到一条错误消息:

  

类型'System.InvalidOperationException'的未处理异常   发生在Name Database.exe

中      

其他信息:创建表单时出错。看到   Exception.InnerException以获取详细信息。错误是:对象引用   没有设置为对象的实例。

这是我的代码:

Public Class Form1
Dim member As String = TextBoxName.Text
Private Sub ButtonAdd_Click(sender As Object, e As EventArgs) Handles ButtonAdd.Click
    ListBoxName.Items.Add(member & " " & TextBoxDate.Text)
    TextBoxDate.Text = ""
    TextBoxName.Text = ""
End Sub

Private Sub ButtonRemove_Click(sender As Object, e As EventArgs) Handles ButtonRemove.Click
    ListBoxName.Items.Remove(ListBoxName.SelectedItem)
End Sub

Private Sub ButtonCheck_Click(sender As Object, e As EventArgs) Handles ButtonCheck.Click
    If ListBoxName.Items.Contains(member & " " & Date.Today.ToString) Then
        MsgBox(ListBoxName.Items.Contains(Date.Today.ToString) & "membership needs to be renewed")
    End If
End Sub
End Class

1 个答案:

答案 0 :(得分:1)

 Dim member As String = TextBoxName.Text

这不起作用,TextBoxName变量在执行此赋值时尚未初始化。您必须使用构造函数,如下所示:

 Dim member As String

 Public Sub New()
    InitializeComponent()
    member = TextBoxName.Text
End Sub

设置TextBoxName控件引用的是InitializeComponent()。请注意,它仍然不太可能工作,用户尚未设置Text属性。所以成员将包含一个空字符串。除非你给设计师一个价值。这表明这更可能是正确的:

 Dim member As String = String.Empty