Fill dataGridView thank's to backGroundWorker

≯℡__Kan透↙ 提交于 2019-12-05 10:23:16

You can't update the UI from a BackgroundWorker thread.

You need to send an event to the UI and then have something like:

private void EventHandler(object sender, YourEventArgs e)
{
    if (this.dataGridView1.InvokeRequired)
    {
        this.dataGridView1.Invoke((MethodInvoker)delegate { this.AddToGrid(e.YourData); });
    }
    else
    {
        this.AddToGrid(e.YourData);
    }
}

The DataGridView is not thread safe. However, setting the DataSource if the data is already available should be fast enough.

I would recommend:

  1. Only use your BackgroundWorker to load the data in another thread

  2. Set the DataSource and the other modifications of the datagridview in the RunWorkerCompleted Event (you can pass the result from the DoWork method to the Completed event by setting

    e.Result = ActeServices.getAllActes(0, 40);

  3. Optional: Set dataGridView1.AutoGenerateColumns to false and manually add the columns either in the Windows Forms Designer or in code to avoid flicker.

It is because GUI stuff cannot be modified from other threads than the GUI thread. To fix this, you need to invoke the changes on the GUI thread by using the Dispatcher.

The DataGrid should be setup beforehand, so all you do in your async operation is fill the data.

var data = ActeServices.getAllActes(0, 40);

Dispatcher.BeginInvoke( new Action( () => { dataGridView1.DataSource = data; }))

The BackgroundWorker class was designed to run a long-standing operation on a background thread. Since you are only allowed to access UI components from the thread that created them, you can use the RunWorkerCompleted event of the BackgroundWorker class to update your UI once your DoWork handler has completed. Also, you can safely update a progress UI using the ProgressChanged event of the BackgroundWorker class.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!