今天在开发C#winform的时候动态添加控件button,直接抛出异常错误:System.ArgumentException:“在某个线程上创建的控件不能成为在另一个线程上创建的控件的父级。”

大概的意思就是如果使用了多线程,那么子线程创建的控件不能往主线程上的容器添加.

这时候怎么办,通过委托来解决,直接上代码

        async void BindDailyTasks()
        {
            flowLayoutPanel1.Controls.Clear();
            await Task.Run(() =>
            {
                var list = DAL.Tasks.Instance.GetDailyTasks();
                for (int i = 0; i < list.Count; i++)
                { 
                    Model.Tasks item = list[i];
                    this.Invoke(new MethodInvoker(delegate { AddItem(item); }));
                }
            });
        }

        public void AddItem(Model.Tasks item)
        {
            var lbl = new ButtonX();
            lbl.TextAlignment = eButtonTextAlignment.Left;
            lbl.Text = item.PlaceNo ; 
            lbl.BackColor = Color.Transparent;
            lbl.Name = Guid.NewGuid().ToString(); 
            //lbl.Location = new System.Drawing.Point(52, height + (i * height));
            lbl.Size = new System.Drawing.Size(180, 39);
            lbl.Font = new System.Drawing.Font("微软雅黑", 13.5F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(134))); 
            lbl.Tag = item;
            lbl.Click += buttonX1_Click;
            flowLayoutPanel1.Controls.Add(lbl);
            Application.DoEvents();
        }

代码差不多就是这样.

以上就是【C#在某个线程上创建的控件不能成为在另一个线程上创建的控件的父级】的全部内容了,欢迎留言评论进行交流!

赞(0) 踩(0)

与本文相关的软件

发表我的评论

最新评论

  1. 暂无评论