[英]Loop through all Controls and Clear desired
您好,我試圖在我的panel1的控件中找到所需的標簽。 我所有的標簽都被命名為“ lbl0”,“ lbl1”,依此類推。
因此,我嘗試遍歷所有這些標簽,直到找到正確的標簽:
Control DelCon(string Name)
{
foreach (Control c in panel1.Controls)
if (c.Name == Name)
{
c.Controls.Clear(); // this should delete the control
}
return null;
}
但是最后,即使c.Name == Name
,也不會刪除該控件。
有人可以幫我解決這個問題嗎?
提前致謝。
您不需要任何循環。 您的面板中包含一個Controls
集合。 只需傳入控件名稱即可獲得控件:
public Control DelCon(string name)
{
Control c = panel1.Controls[name];
panel1.Controls.RemoveByKey(name);//Using RemoveByKey is the best choice
return c;
}
快速修復上面的代碼
Control DelCon(string Name)
{
Control toRemove;
foreach (Control c in panel1.Controls)
{
if (c.Name == Name)
{
toRemove = c;
break;
}
}
if(toRemove != null)
panel1.Controls.Remove(toRemove);
return null;
}
您的原始代碼從您在子控件的面板集合中找到的控件中刪除了所有子控件(如果有)。 附帶說明,當您遍歷該集合時,不能從該集合中刪除元素。 因此,快速解決方案是復制控件的引用以從循環中刪除並退出,並在退出循環后刪除控件(如果找到)
上面的代碼可以使用Linq縮短
Control toRemove = panel1.Controls.Where(x => x.Name == Name).SingleOrDefault();
if(toRemove != null)
panel1.Controls.Remove(toRemove);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.