Max Eisenhardt
Max Eisenhardt

Reputation: 462

DataBinding Grid with data from another thread

I have a data structure(bindingList)that receives data from a another thread with I've bound to a dataGridView which is throwing a cross thread exception. how do I invoke a dataGridView which is dataBound? This is a winForm project. Here's an example of what I'm talking about for clarity:

DataStore dStore = new DataStore();
dStore.ReceiveData += new ReceiveDataEventHndlr(data);
BindingList<mydataobj> myDataStructure = new BindingList<mydataobj>();
dataGridView.DataSource = myDataStructure;

// here's my cross threading issue
private void data(string s, double d)
{
    myDataStructure.Add(new MyDataObj(s,d));
}

Upvotes: 1

Views: 773

Answers (1)

Jonathon Reinhart
Jonathon Reinhart

Reputation: 137398

You need to use Control.Invoke when modifying Controls from another thread:

private void data(string s, double d)
{
    if (this.InvokeRequired) {
        this.Invoke(new Action( () => {data(s, d);} ));
        return;
    }
    myDataStructure.Add(new MyDataObj(s,d));
}

First, you check to see if Control.InvokeRequired. If so, then call Invoke() with a delegate to the same function, and then return. It will re-enter the function from the GUI thread, InvokeRequired will be false, and the control will be updated.

Upvotes: 3

Related Questions