Click here to Skip to main content
14,327,370 members
Rate this:
Please Sign up or sign in to vote.
See more:
Hi Friends...

I need to load some datas to datagridview.Its little time consuming. so i decide to start a thread. so i created a thread instance on form load event and call time consuming function.But its throwing an error
Cross-thread operation not valid: Control '' accessed from a thread other than the thread it was created on.

My code is as follows.
In the form load event
Thread primarythrd = new Thread(primaryload);
                primarythrd.IsBackground = true;
                primarythrd.SetApartmentState(System.Threading.ApartmentState.STA);
                primarythrd.Start();


primaryload function
public void primaryload()
        {
//this line of code gives error.
dataGridView1.Rows.Add(item, malecount, femalecount, malecount + femalecount, Math.Round(calc, 0));
}


How can i solve this error. whats the best method to load huge data to UI without tampering the performance.
Posted
Updated 19-Feb-15 5:00am
v2
Rate this:
Please Sign up or sign in to vote.

Solution 1

I would suggest creating a delegate to invoke a method on just the data grid view.

One note: The columns at least need to be present (or created first in that invoke before the rows).

private void Load() {
Thread primarythrd = new Thread(primaryload);
    primarythrd.IsBackground = true;
    primarythrd.SetApartmentState(System.Threading.ApartmentState.STA);
    primarythrd.Start();
}

delegate void AddRows(DataGridView view);
public void primaryload()
        {
//this line of code gives error.
//dataGridView1.Rows.Add(item, malecount, femalecount, malecount + femalecount, //Math.Round(calc, 0));
AddRows addRows = new AddRows(DoRowAdd);
this.Invoke(addRows, dataGridView1);
}

private void DoRowAdd(DataGridView view) {
    if (view.InvokeRequired) {
        AddRows rows = new AddRows(DoRowAdd);
        this.Invoke(rows, new object[] { view });
    }
    else {
        for (int i = 0; i < 100; i++) {
            view.Rows.Add(item, malecount, femalecount, malecount + femalecount, //Math.Round(calc, 0));
        }
    }
}
   
Comments
jinesh sam 19-Feb-15 23:51pm
   
@Ramza Thanks...
Rate this:
Please Sign up or sign in to vote.

Solution 2

This Code block help me to solve the issue
this.Invoke((MethodInvoker)delegate
            {
                this.dataGridView1.Rows.Add(item, malecount, femalecount, malecount + femalecount, Math.Round(calc, 0));
            });
   
Comments
Ramza360 20-Feb-15 10:35am
   
That is the shorter way about it :)

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)




CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100