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
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With