views:

140

answers:

1

Hi!

I Have one Form (LoginForm) which has a Background Worker Monitoring a database for new entries.

Then I have another Form (AdminForm) which I need to signal to update its datagrids whenever new data is available.

I could poll the database in the AdminForm too, but considering that LoginForm is already doing some polling, which can be costly, I just want to signal AdminForm to update the DataGridViews with the new data.

You may ask, why is LoginForm doing the polling when youre showing the stuff in the AdminForm? Well, LoginForm is actually processing the data and sending it over the Serial Port :$ heheh. I want it to be able to process the data without having an administrator logged in all the time.

+2  A: 

You could have your background worker signal progress (WorkerReportsProgress property set to true, then calling ReportProgress).

In that event handler (OnProgressChanged), invoke another public event you create that signals receivers that data should be updated. Your admin form could subscribe to that event.

As I'm not quite sure whether the OnProgressChanged event is invoked in the context of the main thread or in the context of the background worker's thread, I'd suggest you use this.Invoke when actually doing the UI update.

EDIT
Using OnProgressChanged and another event, do the following:

In the Form1 class, declare a new event like

public event EventHandler DataChanged;

Also, declare a method that raises the event:

protected void OnDataChanged()
{
    if (DataChanged != null)
        DataChanged(this, EventArgs.Empty);
}

Then, in the OnProgressChanged method, call your OnDataChanged method.

All you need to do now is:

  1. Attach Form2 to the event in Form1 using something like form1.DataChanged += new EventHandler....
  2. In that event handler, update your controls in Form2

You might for example pass the current instance of Form1 to the constructor of Form2 when it is created and attach the event handler in the constructor of Form2. There are other options as well.

EDIT 2
Thinking about it: Why don't you put the polling code into a separate class that provides an event whenever data changes. Then you can attach both Form1 and Form2 to these events. This would make Form2 independant from Form1.

Thorsten Dittmar
ProgressChanged event is invoked in the context of the UI thread
Mitch Wheat
Ah thanks for this hint. I would have had to try it myself next time, but I'll remember now :-)
Thorsten Dittmar
hmm.... a little of that went over my head.OnProgressChanged will run on Form1's UI thread... but it's still illegal to access datagrids on Form2 from there. which is exactly my problem.i'm not familiar with the .Invoke method. How would i use it in respect to my datagrids in Form2, updating them from Form1?Thanks for the response!
FezKazi
I edited my answer to provide more information.
Thorsten Dittmar