-1

Exception:

Object reference not set to an instance of an object.

Code:

    For Each p As Panel In Me.Controls.OfType(Of Panel)()
        arr.Add(p.BackColor.ToString())
        Me.Controls.Remove(p)
    Next

The line:

arr.Add(p.BackColor.ToString())


How can I fix this thing?

eightShirt
  • 1,457
  • 2
  • 15
  • 29
AoTw
  • 123
  • 1
  • 5
  • 11
  • 2
    It's not a part of your question, but be careful with that `Me.Controls.Remove(p)` line. It won't clear out all of the panels since you are changing the collection as you iterate through them. Also, it won't get rid of the panels from memory. For that, you need to call `Dispose()` on them. – LarsTech Jun 20 '12 at 19:37
  • 1
    To fix the possible `Remove` problem, just change `.OfType(Of Panel)()` to `.OfType(Of Panel)().ToArray()`. – Ry- Jun 20 '12 at 20:02
  • Possible duplicate of [What is a NullReferenceException, and how do I fix it?](http://stackoverflow.com/questions/4660142/what-is-a-nullreferenceexception-and-how-do-i-fix-it) – Andrew Morton Dec 17 '16 at 19:01

1 Answers1

3

You probably declared arr something like this:

Dim arr As List(Of String)

You need to initialize the variable to an instance of List(Of String) before you can use it. Change it to:

Dim arr As New List(Of String)
Ry-
  • 218,210
  • 55
  • 464
  • 476