Click here to Skip to main content
15,886,578 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
In my Application I had A requirement of Notifying the user about the Pending applications
So in the mdiParent I set a Background worker which keeps quering the database to get any pending application and if it finds any display it on the Tooltip on the MdiParent




C#
private void button1_Click(object sender, EventArgs e)
           {
               backgroundWorker1.RunWorkerAsync(2000);
           }
      private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
           {
               fillnotification();
           }


           public void fillnotification()
           {
               int pending = 0;
               if( Program.USERPK!=0){

                   DataTable dt = nftrans.getnotification();
                   pending = dt.Rows.Count;

                   String message = "You Have  " + pending + " Applications Pending For Approval";

                //   toolTip1.SetToolTip(lblStatus , message);
                  toolTip1.Show(message , this, lblStatus.Location);




               }
           }


but when Iam running the solution I am getting an exception

Cross-thread operation not valid: Control 'MainForm' accessed from a thread other than the thread it was created on.
I understood its due to two different thread but Cannot sort this out can any one suggest a help .I tried the ideas I read in related questions But cannot find a correct solution
Posted

1 solution

You can only access Controls from the thread they were created on - the UI thread. Attempting to do so from another thread (such as the BackgroundWorker you are using) will give you an error.

There are two ways to do this:
1) You could use Invoke to move the access back to the UI thread.
2) You could tell the main thread it has info.

Personally, I would do the second, via the BackgroundWorker Progress reporting mechanism:
Set the WorkerReportsProgress property to true.
Handle the worker ProgressChanged event.
In the handler, get the ProgressChangedEventArgs.ProgressPercentage value and set your tool tip.
In your worker method, replace the tooltip code with a call to the worker.ReportProgress(pending) instead.
 
Share this answer
 

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