0

我想知道下面的 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()

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

4

2 回答 2

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
于 2012-08-09T04:19:45.550 回答
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
于 2012-08-09T04:18:33.257 回答