0

I am beginner in VB. I am trying to find the indexes of selected values of ListBox1 and print those indexes in ListBox2. I am not specifying the length of array. I want it to take the values dynamically. Here is the code..

  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

The exception I am getting at line a(b) = x is as follows

NullReferenceException was unhandled
Object reference not set to an instance of an object.

Can you kindly help me in this?

Uwe Keim
  • 39,551
  • 56
  • 175
  • 291
METALHEAD
  • 2,734
  • 3
  • 22
  • 37

2 Answers2

2

You either remove a() completely or else define a size for it:

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
Keith Mifsud
  • 725
  • 5
  • 16
  • Thanks for you valuable comment. In other languages we can declare the array variable without specifying size and we can initialize the values. It automatically considers the length. Is this feature missing in VB..?? – METALHEAD May 24 '16 at 09:34
  • 1
    Yes, alot of languages do not handle dynamic length on arrays. But there are a lot of workarounds so its not really a limitation. For example in VB (any .NET language), you can use Lists which internally create arrays and appear as dynamic – Keith Mifsud May 24 '16 at 09:40
1

You should set a like this:

Dim a As Integer()

And then do a ReDim to initialise:

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

Or however long you think a should be.

Robin Mackenzie
  • 18,801
  • 7
  • 38
  • 56
  • Thanks for you valuable comment. In other languages we can declare the array variable without specifying size and we can initialize the values. It automatically considers the length. Is this feature missing in VB..?? – METALHEAD May 24 '16 at 09:34
  • 1
    Agree about other languages - you can also do this: `Dim a(4) As Integer` or also you might try `Dim a(ListBox1.Items.Count) As Integer` – Robin Mackenzie May 24 '16 at 09:39
  • 1
    Personally I would prefer to use a List e.g. `Dim MyList as New List(Of Integer)` and then use `MyList.Add(123)` or similar – Robin Mackenzie May 24 '16 at 09:40