1

I am trying to delete Controls dynamically, without knowing the parent. But I keep getting a "System.NullReferenceException" in mscorlib.dll when I debug.

My Code:

//Delete Controls
        List<PictureBox> toDelete = severalControlsFromDifferentPanels;
        for (int i = toDelete.Count - 1; i >= 0; --i)
        {
            Control parent = toDelete[i].Parent;
            parent.Controls.Remove(toDelete[i]);
        }

What am I missing here? Am I overseeing something obvious? thanks in advance!

Sip
  • 373
  • 1
  • 6
  • 22

2 Answers2

3

Check if pictureBox has parent before accessing it:

foreach(PictureBox pictureBox in toDelete)
    if (pictureBox.Parent != null)
        pictureBox.Parent.Controls.Remove(pictureBox);

To make this code even more readable you can create extension method:

public static void RemoveFromParent(this Control control)
{
    if (control == null)
       throw new ArgumentNullException();

    if (control.Parent == null)
        return;

    control.Parent.Controls.Remove(control);
}

Thus removing controls will look like:

foreach(PictureBox pictureBox in toDelete)
    pictureBox.RemoveFromParent();
Sergey Berezovskiy
  • 232,247
  • 41
  • 429
  • 459
  • 1
    @Selman22 oops, didn't see error message. I believe that is caused by control without parent. Changed code, thanks – Sergey Berezovskiy Feb 10 '14 at 14:42
  • 1
    You were right! Some controls actually had no parent. I used this weird for-loop because of this post: http://stackoverflow.com/a/1582317/2958399 (i see now, its not even necessary ;)) Thanks for the quick answer! – Sip Feb 10 '14 at 14:47
0

Something is null; trying to access a property or method on a null object will throw that exception.

Place a breakpoint on the first line and step through your code.

 List<PictureBox> toDelete = severalControlsFromDifferetPanels;

 // if severalControlsFromDifferetPanels is null, then toDelete.Count will throw
 for (int i = toDelete.Count - 1; i >= 0; --i)
 {
     // if toDelete[i] is null, then accessing .Parent will throw
     Control parent = toDelete[i].Parent;

     // if parent is null, then .Controls will throw
     parent.Controls.Remove(toDelete[i]);
 }

We can't tell any more than that from the code you've provided.

Grant Winney
  • 65,241
  • 13
  • 115
  • 165