在动态初始化数组中的值时获取异常

时间:2016-05-24 09:02:14

标签: arrays vb.net winforms

我是VB的初学者。我试图找到ListBox1的选定值的索引并在ListBox2中打印这些索引。我没有指定数组的长度。我希望它动态地获取值。这是代码..

  Private Sub Button2_Click(sender As System.Object, e As System.EventArgs) Handles Button2.Click

    Dim a() As Integer
    Dim b As Integer = 0

      For x As Integer = 0 To ListBox1.Items.Count - 1

          If ListBox1.GetSelected(x) = True Then
              a(b) = x
              b = b + 1
        End If
    Next

    For x As Integer = 0 To a.Length - 1

        ListBox2.Items.Add(a(x))

    Next

   End Sub

我在第a(b) = x行获得的例外情况如下

  

NullReferenceException未处理   对象引用未设置为对象的实例。

你能帮助我吗?

2 个答案:

答案 0 :(得分:2)

您要么完全删除a(),要么为其定义尺寸:

Private Sub Button2_Click(sender As System.Object, e As System.EventArgs) Handles Button2.Click
    ListBox2.Items.Clear()
    For x As Integer = 0 To ListBox1.Items.Count - 1    
        If ListBox1.GetSelected(x) = True Then
            ListBox2.Items.Add(x)
        End If
    Next    
End Sub

答案 1 :(得分:1)

你应该这样设置:

Dim a As Integer()

然后做一个ReDim初始化:

ReDim a(0 to ListBox1.Items.Count - 1)

或者你认为应该是多久。