Click here to Skip to main content
15,887,350 members
Please Sign up or sign in to vote.
4.00/5 (1 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
C#
Thread primarythrd = new Thread(primaryload);
                primarythrd.IsBackground = true;
                primarythrd.SetApartmentState(System.Threading.ApartmentState.STA);
                primarythrd.Start();


primaryload function
C#
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

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).

C#
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));
        }
    }
}
 
Share this answer
 
Comments
jinesh sam 19-Feb-15 23:51pm    
@Ramza Thanks...
This Code block help me to solve the issue
C#
this.Invoke((MethodInvoker)delegate
            {
                this.dataGridView1.Rows.Add(item, malecount, femalecount, malecount + femalecount, Math.Round(calc, 0));
            });
 
Share this answer
 
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, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900