Search code examples
c#data-bindingdatagridviewdatatable

c# datagridview red cross


I have a datagridview and datatable. I use the datatable as a datasource of the datagridview. I add and update the data using threads as below. And if I am done with the data I remove it. But two times there were big red x in front of the datagridview. I couldn't find out why? Below are my sample.

Note: This does not always occur, I got this error only two times but I need to handle! Thanks in advance.

  Thread listData;
  DataTable dt = new DataTable();
  Form1_load()
  {
    dataGridview.DataSource = dt;
  }

   public void ListData()
   {
      foreach(var item in data)
      {
          if(item.delete)
          { 
            var row = dt.Rows.Find(item.id); 
            if(row != null) { row.Delete();}
            continue;
          }

          listData = new Thread(delegate() { InsertOrUpdateData(item.Id); });
           listData.Start(); listData.Join();
       }

   }

      public void InserOrUpdateData(int id)
      {
         // Here I retrieve some data from database
         // and insert or update to the datatable
          // like dt.Rows.Add(fields) and dt.Rows.Find(id)["fieldName"] = "new Value"
      }

Solution

  • You need to use Invoke method

    if (gridView.InvokeRequired)
        gridView.Invoke(new MethodInvoker(() => gridView.DataSource = YOUR_DATASOURCE));
    else
        gridView.DataSource = YOUR_DATASOURCE;