C#里怎么用代码删除动态生成的按钮

如题;
for (int i = 0; i < 9; i++)
{
for (int j = 0; j < 9; j++)
{
Button bt = new Button();
bt.Size = new Size(20, 20);
bt.Location = new Point(i * 20, j * 20 + 50);
bt.TabStop = false;
Controls.Add(bt);
}
}
像这样生成的9X9的按钮,怎样用代码全部删除,最好这个代码在一个click事件里,像一键清除那样!求大神指点!

第1个回答  2013-05-27
private void button1_Click(object sender, EventArgs e)
{
Clear(this);
//label1.Text = i.ToString();
}

private void Clear(Control ctrl)
{

foreach (Control c in Controls)
{
if (c is Button)
{
c.Dispose();
//i++;
Clear(c);
}
}
}本回答被提问者采纳
第2个回答  2013-05-27
如果你动态生成的控件是放在一个容器里面的(panel),那么直接panel.Controls.Clear();
第3个回答  2013-05-27
创建按钮的时候,把它们都存到一个List里面,删除的时候就方便了。
第4个回答  2013-05-27
Panel p = new Panel();
public Form1()
{
InitializeComponent();
p.Width = 500;
p.Height = 500;
p.BackColor = Color.Black;
p.Location = new Point(0, 0);
for (int i = 0; i < 9; i++)
{
for (int j = 0; j < 9; j++)
{
Button bt = new Button();
bt.Size = new Size(20, 20);
bt.Location = new Point(i * 20, j * 20 + 50);
bt.TabStop = false;
bt.Click+=new EventHandler(bt_Click);
p.Controls.Add(bt);
}
}
this.Controls.Add(p);
}

private void bt_Click(object sender, EventArgs e)
{
Button b=(Button)sender;
b.Hide();
}
请采纳!
第5个回答  2013-05-27
就跟楼下说的那样,最好放在一个panel(面板)里,这样只要清除面板就可以了,清楚代码楼下已经列出

相关了解……

你可能感兴趣的内容

本站内容来自于网友发表,不代表本站立场,仅表示其个人看法,不对其真实性、正确性、有效性作任何的担保
相关事宜请发邮件给我们
© 非常风气网