Reputation: 1552
Im trying to databind my data grid view from a timer using multi threading. THe timer is there as we need it to show live data.
The code im using is -
private void Form1_Load(object sender, EventArgs e)
{
dt = JobManager.GetTodaysJobs();
trd = new Thread(StartTimer);
trd.Start();
}
void StartTimer()
{
timer1.Start();
LoadData();
}
void LoadData()
{
dt = JobManager.GetTodaysJobs();
dataGridView1.AutoGenerateColumns = false;
dataGridView1.DataSource = dt;
}
private void timer1_Tick(object sender, EventArgs e)
{
LoadData();
}
However, I get the following error -
Cross-thread operation not valid: Control 'dataGridView1' accessed from a thread other than the thread it was created on.
Any ideas how I can get around this?
Cheers
Upvotes: 3
Views: 3222
Reputation: 11577
You cannot update UI elements from A thread that is not the creator of these objects.
change your method like this:
void LoadData()
{
if (InvokeRequired)
Invoke(new MethodInvoker(InnerLoadData));
}
void InnerLoadData()
{
dt = JobManager.GetTodaysJobs();
dataGridView1.AutoGenerateColumns = false;
dataGridView1.DataSource = dt;
}
Upvotes: 6