Mark
Mark

Reputation: 7818

Refresh a windows form, even when not the active window

I am trying something quite basic.

I have 3 labels on my windows form, which I would like to populate from 3 separate queries from the database, but also to show the user that something is happening, I would like to show each label as the data is available from the respective query.

To do this, I can use:

Form.ActiveForm.Refresh();

However, if the user clicks on any other window on their desktop, that command fails, with the "object not set" error.

Is there any way that I can refresh the labels on the Form, even if the form window is not the active window?

// Breach within next hour
DataTable tbBreach = (get info from database)
tbBreach.DefaultView.Sort = "Assignee ASC";
dgBreach.DataSource = tbBreach;
lbBreach2.Text = tbBreach.Rows.Count.ToString();
Form.ActiveForm.Refresh();  //Would like to update this form field now, and show it on the form

// Breach within next 24 hour
DataTable tbBreach24 = (get info from database)
tbBreach24.DefaultView.Sort = "Assignee ASC";
dgBreach24.DataSource = tbBreach24;
lbBreach24.Text = tbBreach24.Rows.Count.ToString();
Form.ActiveForm.Refresh();

Thank you,

Mark

Upvotes: 2

Views: 34614

Answers (1)

digEmAll
digEmAll

Reputation: 57210

The labels will be refreshed automatically at the end of the elaboration.

You probably want to force the refresh to update labels in the middle of the elaboration and you can do that simply using this.Refresh() since I suspect the method is located inside the form class.

However, when you have a long elaboration and you need to keep the UI updated and reactive (i.e. not frozen) the suggested approach is to avoid elaboration on the UI thread, but to delegate the work on another thread using a BackGroundWorker.

Here's a working example of BackGroundWorker usage.

Upvotes: 4

Related Questions