[英]Remove Controls from List with different Parents
I am trying to delete Controls dynamically, without knowing the parent. 我试图动态删除控件,而又不知道其父级。 But I keep getting a "System.NullReferenceException" in mscorlib.dll when I debug.
但是在调试时,我在mscorlib.dll中不断收到“ System.NullReferenceException”。
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: 在访问pictureBox之前,先检查它是否具有父级:
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
; 东西是
null
; trying to access a property or method on a null object will throw that exception. 尝试访问null对象的属性或方法将引发该异常。
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. 从您提供的代码中我们只能说出更多。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.