Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

databind datagridview in multithreadded application

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

like image 622
dynamicuser Avatar asked Mar 05 '26 12:03

dynamicuser


1 Answers

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;
}
like image 131
No Idea For Name Avatar answered Mar 08 '26 03:03

No Idea For Name



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!