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!
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();
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.