Click here to Skip to main content
15,896,489 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi
I have a Class which contains a BackgroundWorker to update the data in Form from database. Also I have a another class which is used to create a context menu and its events.
I have to call backgroundworker from the event in the second class. Is it Possible to do it.


sample Code

class Main
C#
public partial class FormMain: Form
{
 private void bwMain_DoWork(object sender, DoWorkEventArgs e)
 {
   //Fetch data

 }
 private void bwMain_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
 {
   //Update UI  
 }
 
}

public class MenuMain
{
 MenuMain()
 {
  MenuItem miPayLoan = new MenuItem("Menu1", new EventHandler(Menu1_Click));
 }
  private void miPayLoan_Click(object sender, EventArgs e)
{
  //do some operations 
  //here call backgroundworker of above class to update Form   
}
}




Thanks ..
Posted

Sure.
C#
private void miPayLoan_Click(object sender, EventArgs e)
{
    //do some operations
    //here call backgroundworker of above class to update Form
    MainForm.StartFormUpdatingMethod();
}
Of course, you need a bit more code. In your FormMain.cs:
C#
public partial class FormMain : Form
{
    // This may also reside in FormMain.Designer.cs,
    //   depends on how you added it to the project.
    BackgroundWorker bwMain = new BackgroundWorker();

    public void StartFormUpdatingMethod()
    {
        bwMain.StartAsync();
    }

    // What you showed already
}
To make this work, you need a reference to the instance of FormMain available in miPayLoan_Click(). If it resides within the FormMain class itself, that's trivial. Otherwise you'll have to provide a reference.
 
Share this answer
 
Comments
Geo Jackson 29-Jul-13 9:28am    
Acutally i have a function inside backgroundworker which fetch data from database. when the function fetches data it throws error "Non-static method requires a target.". Am i missing something.
lukeer 30-Jul-13 3:04am    
From that error message I read that it has nothing to do with the BackgroundWorker, but with the code inside its DoWork() method. That code is calling a method in a class. That method is not static. And the code is calling it on the class itself, not on an instance thereof.

Therefore either use an instance to call the method, or call a static method on the class.

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