C# Controls created on one thread cannot be parented to a control on a different thread
15,930
Solution 1
You cannot update UI thread from another thread:
private void RUN()
{
if (this.InvokeRequired)
{
this.BeginInvoke((MethodInvoker)delegate()
{
Label l = new Label(); l.Location = new Point(12, 10);
l.Text = "Some Text";
this.Controls.Add(l);
});
}
else
{
Label l = new Label();
l.Location = new Point(12, 10);
l.Text = "Some Text";
this.Controls.Add(l);
}
}
Solution 2
You need to use BeginInvoke to access the UI thread safely from another thread:
Label l = new Label();
l.Location = new Point(12, 10);
l.Text = "Some Text";
this.BeginInvoke((Action)(() =>
{
//perform on the UI thread
this.Controls.Add(l);
}));
Solution 3
Your are trying to add control to a parent control from a different thread , controls can be added to parent control only from the thread parent control was created!
use Invoke to access the UI thread safely from another thread:
Label l = new Label();
l.Location = new Point(12, 10);
l.Text = "Some Text";
this.Invoke((MethodInvoker)delegate
{
//perform on the UI thread
this.Controls.Add(l);
});
Author by
BOSS
Updated on July 29, 2022Comments
-
BOSS almost 2 years
I am running a thread and that thread grabs information and create labels and display it, here is my code
private void RUN() { Label l = new Label(); l.Location = new Point(12, 10); l.Text = "Some Text"; this.Controls.Add(l); } private void button1_Click(object sender, EventArgs e) { Thread t = new Thread(new ThreadStart(RUN)); t.Start(); }
The funny thing is that i had a previous application that has a panel and i used to add controls to it using threads without any issue, but this one won't let me do it.
-
BOSS over 11 yearsCouldn't use it Error 1: Using the generic type 'System.Action<T>' requires 1 type arguments