Update UI controls in Form class from another class

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?
 
P

Peter Ritchie [C# MVP]

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.
 
C

Curious

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;

}
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top