Reputation: 13
I have one button with following code
new Thread(() =>
{
DataTable table = Finish(txtTest.Text);
//dgwTest.DataSource = table
}).Start();
and I would like to set datagridview data source but I get an "cross thread" exception. Anyone know how can I avoid this?
Upvotes: 1
Views: 1747
Reputation: 27913
string source = txtTest.Text;
new Thread(() =>
{
DataTable table = Finish(source);
dgwTest.Invoke ((Action) (() => dgwTest.DataSource = table));
}).Start();
Upvotes: 5
Reputation: 33143
You need to use the Invoke method on the DataGridView
private delegate void SetDGVValueDelegate(DataTable table);
private void button1_Click(object sender, EventArgs e)
{
new Thread(() => {
DataTable table = Finish(txtTest.Text);
SetDGVValue(table);
}).Start();
}
private void SetDGVValue(DataTable table)
{
if (dataGridView1.InvokeRequired)
{
dataGridView1.Invoke(new SetDGVValueDelegate(SetDGVValue), table);
}
else
{
dataGridView1.DataSource = table;
}
}
Upvotes: 0