在winform窗体上拖一个flowLayoutPane,一个Button,项目中再创建一个用户控件UcControl,用户控件上放几十个子控件

private void button1_Click(object sender, EventArgs e)
{
try
{
DateTime startTime = DateTime.Now; flowLayoutPanel1.Controls.Clear();
for (int i = ; i < Controlcount; i++)
{
UcControl v = new UcControl();
v.Width = ;
v.Height = ;
flowLayoutPanel1.Controls.Add(v); }
slExecutedTime.Text = (DateTime.Now - startTime).ToString();
}
catch (Exception exception)
{
Console.WriteLine(exception);
throw;
}
}

使劲点按钮,过一会弹出创建句柄出错。解决办法,加上红色部分就好了,再使劲点也不会出问题。

private void button1_Click(object sender, EventArgs e)
{
try
{
DateTime startTime = DateTime.Now;
DeleteChilds(flowLayoutPanel1);
flowLayoutPanel1.Controls.Clear();
for (int i = ; i < Controlcount; i++)
{
UcControl v = new UcControl();
v.Width = ;
v.Height = ;
flowLayoutPanel1.Controls.Add(v); }
slExecutedTime.Text = (DateTime.Now - startTime).ToString();
}
catch (Exception exception)
{
Console.WriteLine(exception);
throw;
}
}
      private void DeleteChilds(Control control)
        {
            while (control.Controls.Count > 0)
            {
                if (control.Controls[0] != null)
                {
                    //DeleteChilds(control.Controls[0]);
                    control.Controls[0].Dispose();
                }
                
            }
        
        }
 
05-11 11:30