[英]C# : how to modify properties of dynamically created controls like panels etc
[英]Clear dynamic controls from dynamically created panels
我在winforms中有以下程序:
我想清除面板上看到的兩個按鈕。
我的代碼似乎只能清除最后一個面板中的最后一個按鈕。 我需要清除所有面板。 我在這里想念的是什么:
public Form1()
{
InitializeComponent();
}
Panel pnl1;
Panel pnl2;
Button btn;
private void createPanels(int spacing)
{
pnl1 = new Panel();
pnl1.Location = new Point(5, spacing);
pnl1.BorderStyle = BorderStyle.FixedSingle;
pnl1.Size = new Size(85, 93);
this.Controls.Add(pnl1);
pnl2 = new Panel();
pnl2.Location = new Point(91, spacing);
pnl2.BorderStyle = BorderStyle.FixedSingle;
pnl2.Size = new Size(85, 93);
this.Controls.Add(pnl2);
}
void addCons()
{
btn = new Button();
btn.Size = new Size(40, 20);
btn.Location = new Point(5, 5);
}
private void Form1_Load(object sender, EventArgs e)
{
addCons();
createPanels(5);
pnl1.Controls.Add(btn);
addCons();
createPanels(99);
pnl1.Controls.Add(btn);
}
private void button1_Click(object sender, EventArgs e)
{
pnl1.Controls.Clear();
}
僅清除一個面板的原因是因為每次調用createPanels
時都要重新分配pnl1
變量的值。 避免在此處使用全局Panel
變量,並考慮將面板存儲在列表中。
//class level variable
List<Panel> allPanels = new List<Panel>();
//...
Panel pnl1 = new Panel();
//...panel code
this.Controls.Add(pnl1);
allPanels.add(pnl1);
Panel pnl2 = new Panel();
//...panel code
this.Controls.Add(pnl2);
allPanels.add(pnl2);
//..
private void button1_Click(object sender, EventArgs e)
{
foreach(Panel p in allPanels) {
while (p.Controls.Count > 0) p.Controls[0].Dispose();
}
}
另外,您可以遍歷表單上的所有控件並獲得類似的Panels
,但是使用列表可以為您提供更多控件,並且可以避免必須遍歷許多控件。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.