Adding controls using Thread to the Form

G

Guest

My Windows application has a form and a Thread.

Whenever some event occurs i want to add a listview control to the form
using the Thread. But when i try to add it says "Controls created on one
thread cannot be parented to a control on a different thread.".

This is my Code:

public class Form1 : System.Windows.Forms.Form
{
public void AddControl()
{
ListView l = new ListView();
l.Text = "Hello";
this.Controls.Add(l);
}
private void button2_Click(object sender, System.EventArgs e)
{
Thread t = new Thread(new ThreadStart(AddControl));
t.Start();
}

}

Any solution to this problem?
 
T

Truong Hong Thi

For a quick start, try something like this:
private void button2_Click(object sender, System.EventArgs e)
{
Thread t = new Thread(new ThreadStart(ThreadProc));
t.Start();
}
private void ThreadProc()
{
this.Invoke(new MethodInvoker(AddControl));
}

Thi
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top