Refresh a windows form, even when not the active window

33,722

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.

Share:
33,722
Mark
Author by

Mark

Updated on July 09, 2022

Comments

  • Mark
    Mark almost 2 years

    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

    • digEmAll
      digEmAll over 11 years
      In principle, there's no need to refresh since the label should automatically refresh itself whenever you set the Text property. Have you tried to remove the refresh lines ?
    • Mark
      Mark over 11 years
      Hi @digEmAll - yes - if I remove them, the labels don't appear to update until the end of the function (above is executed when someone clicks an "Update Figures" button. It's as if updating the form (or at least refreshing it) is not done at all, until the function has finished - which is why I thought I could add the Refresh() after each label - but that then causes the error, if the user doesn't have the window the form is on, in focus. Thanks a lot.
  • digEmAll
    digEmAll over 11 years
    Added an example of BackGroundWorker.