我有以下代码片段:

private void backgroundWorker1_DoWork(object sender, System.ComponentModel.DoWorkEventArgs e)
    {
        remplirDataGrid();
    }

private void frmChercherActesLoad(object sender, EventArgs e)
        {
            backgroundWorker1.RunWorkerAsync();

        }



 private void remplirDataGrid()
        {
            dataGridView1.DataSource = ActeServices.getAllActes(0, 40);
            dataGridView1.Columns[0].Visible = false;
            dataGridView1.Columns[1].HeaderText = "Code acte";
            dataGridView1.Columns[2].HeaderText = "Désignation";
            dataGridView1.Columns[3].HeaderText = "Pris en charge";
            dataGridView1.Columns[4].HeaderText = "Id article";
            dataGridView1.AutoResizeColumns(DataGridViewAutoSizeColumnsMode.AllCells);
        }

这是getAllActe方法:
public static IEnumerable<Acte> getAllActes(int skipCount, int takeCount)
        {
            var myTableAdapter = new SmartDocDALServices.SmartDocDataSetTableAdapters.actesTableAdapter();
            myTableAdapter.Fill(myDataSet.actes);
            var myResult = from q in myDataSet.actes.AsEnumerable()
                            select new Acte
                            {
                                code = q.code,
                                designation = q.designation,
                                priseEnCharge = q.prise_en_charge,
                                idArticle = q.id_article,
                            };

            if (skipCount != -1)
                myResult.Skip(skipCount);
            if (takeCount != -1)
                myResult.Take(takeCount);
            IEnumerable<Acte> myResultRet = myResult.ToList();
            return myResultRet;

我想做的是一旦运行该应用程序后出现此错误,便使用后台工作程序填充datagridview:



我尝试这个
 private void backgroundWorker1_DoWork(object sender, System.ComponentModel.DoWorkEventArgs e)
    {
      IEnumerable<Acte> result = ActeServices.getAllActes(0, 40);
       backgroundWorker1.ReportProgress(0, result);

    }

    void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
    {

      dataGridView1.DataSource = (IEnumerable<Acte>)e.UserState;
      dataGridView1.Columns[0].Visible = false;
      dataGridView1.Columns[1].HeaderText = "Code acte";
     ***

但是没有及时获得 yield ?我想在BGW加载数据时更新datagrid,将其添加到DGV中。

最佳答案

您无法从BackgroundWorker线程更新UI。

您需要将事件发送到用户界面,然后执行以下操作:

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);
    }
}

关于c# - 填写dataGridView感谢backGroundWorker,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/3127838/

10-12 12:44
查看更多