Actually you should never try to access any Control inside the DoWork.
There are just two ways you would need them inside the DoWork event.
- You want to pick up some value from some control.
- You want to update some control's value.
To pick some value from any control, put such values in variables, so that you don't need to reference the controls from inside the DoWork event. Do that before you call the RunWorkerAsync method (which in turn fires the DoWork event).
If you want to set something in any control, you should use the ReportProgress method to pass your values out of BackgroundWorker. The values you pass from ReportProgress can be accessed from the ProgressChanged event. You can assign those values to your controls or do anything else you want to do with them.
So you do:
This was just a simple example where a string is passed.Code:' Inside DoWork event worker.ReportProgress(10, "Run coding 1") ' In ProgressChanged event Me.lbl1.Text = CType(e.UserState, String)
But in many cases you may want to pass more information than this to the ProgressChanged event.
e.g. you have 10 labels, and you also want to pass which label's text property to set, along with the string value you want to set.
Fortunately, the ReportProgress can pass a value of type Object to the ProgressChanged event. This means that you can pass virtually anything via that method. It can be as small as a string or number, or it can be a complex structure like some class object or array etc.
Below is an example where I pass the control name and its value to set.
1. Create a structure/class which can hold the control name (name of label) and the text value to set.
2. From inside the DoWork event, you pass an object instance of this structure.Code:Public Structure ControlWithText Public ControlName As Control Public Text As String Public Sub New(ByVal ctrl As Control, ByVal text As String) Me.ControlName = ctrl Me.Text = text End Sub End Structure
e.g.
3. Now in your ProgressChanged event, you will have this object available. Just get the control name and the text out of it and do your task appropriately.Code:worker.ReportProgress(10, New ControlWithText(Label1, "Run coding 1")) worker.ReportProgress(20, New ControlWithText(Label2, "Run coding 2"))
Code:If TypeOf e.UserState Is ControlWithText Then Dim cwt As ControlWithText = CType(e.UserState, ControlWithText) cwt.ControlName.Text = cwt.Text End If




icon on the left of the post.
Reply With Quote