Reputation: 73
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"
}
Upvotes: 3
Views: 2211
Reputation: 7150
You need to use Invoke method
if (gridView.InvokeRequired)
gridView.Invoke(new MethodInvoker(() => gridView.DataSource = YOUR_DATASOURCE));
else
gridView.DataSource = YOUR_DATASOURCE;
Upvotes: 2