对象引用未设置为实例,公共数组带有..Split(“,”)

时间:2012-08-09 03:58:35

标签: vb.net arrays split

我想知道以下vb.net代码有什么问题。

Public Class Form10

Public IDs() As String = TextBox1.Text.Split(",")

Private Sub Form10_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
End Sub

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
    For Each id In IDs
        MsgBox(id)
    Next
End Sub

结束班

当我做的时候

Form10.show()

我收到错误“对象引用未设置为实例”

2 个答案:

答案 0 :(得分:1)

您已在类中声明了一个字段,该字段使用相应表单上尚不存在的控件的值进行初始化。在访问字段成员上的初始化程序时,控件未初始化和加载,从而导致错误。

要保留公共ID声明,可以从字段声明中删除初始化,然后将分配移动到Button1_Click事件,如下所示:

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
    IDs=TextBox1.Text.Split(",")
    ' Do something interesting with IDs now...
End Sub

答案 1 :(得分:0)

Public Class Form10
Private Sub Form10_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
End Sub

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
    Dim IDs() As String = TextBox1.Text.Split(",")
    Form1.somefunction(IDs)
End Sub

并在Form1中

  Public Sub somefunction(ByVal IDs() As String)
    For Each id In IDs
        MsgBox(id)
    Next
End Sub