Update UI controls in Form class from another class

  • Thread starter Thread starter Curious
  • Start date Start date
C

Curious

I have two classes:

BulkProcessing.cs
BulkProcessingStatusForm.cs

BulkProcessing uses a background worker to process each row of data.
BulkProcessingStatusForm is a UI form (dialog) that displays the
status of the processing.

Now I have "DoWork" method in BulkProcessing as below:

protected void DoWork(object sender, DoWorkEventArgs args)
{
for (int i = 0; i < mSelectedItems.Count; i++)
{
try
{
//omitted code
}
catch (Exception e)
{
//error handling
}
this.mBackgroundWorker.ReportProgress(i /
mSelectedItems.Count, i);

// How to update the UI controls on the other form
(BulkProcessingStatusFormBase)?
UpdateControls();

}
}

I was advised to use RaiseEvents (to observe events from the UI form).
But I don't know how. Any advice?
 
RaiseEvents is a VB statement.

You can't update controls from your DoWork method because it is not running
on the GUI thread, DoWork runs on a background (threadpool) thread. The
ReportProgress method raises the ProgressChanged event that the form can
subscribe to. You can do whatever you want in your ProgressChanged event
handler because it's guaranteed to be using the GUI thread.
 
Hi Peter,

Thanks for the advice! Could you tell me if the following is what you
have suggested?

// In BulkProcessing
public BulkProcessing(SortableBindingList<IWorkerItemBase>
selectedItems)
{

// Omitted code

// Add event handler to invoke updating UI controls when
there's a change in progress
this.mBackgroundWorker.ProgressChanged += new
ProgressChangedEventHandler(WorkProgressChanged);
}



void WorkProgressChanged(object sender,
ProgressChangedEventArgs e)
{
// Invoke updating UI controls on the form
BulkProcessingStatusForm statusForm = new BulkProcessingStatusForm
();
statusForm.UpdateUIcontrols(sender, e);
}


// In BulkProcessingStatusForm
private void UpdateControls(object sender, EventArgs e)
{

int lFailedReports = 0;
int lPendingReports = 0;
int lSuccessReports = 0;
int lSelectedReports = 0;

GetSummaryData(ref lFailedReports, ref lPendingReports,
ref lSuccessReports, ref lSelectedReports);

this.summaryReportsTextBox.Text =
lSelectedReports.ToString();
this.summaryFailedTextBox.Text =
lFailedReports.ToString();

this.summaryActionLabel.Text = string.Format("{0}{1}:",
Action.Substring(0, 1).ToUpper(), Action.Substring(1));
this.summaryActionTextBox.Text =
lSuccessReports.ToString();
this.summaryActionTextBox.Left = summaryActionLabel.Left +
summaryActionLabel.Width + 6;

}
 
Back
Top