-1

My backgroundWorker doWork's event has many codes to execute.Is it possible to change the label text after each code is executed ?

For example :

     Dim con As New SqlConnection("Data source=" & My.Settings.ip & "," & My.Settings.port & ";Network Library=DBMSSOCN;initial catalog=offpodb;User id=" & My.Settings.username & ";Password=" & My.Settings.password & ";")
    con.Open()
    If connected.Dispatcher.CheckAccess Then
        connected.Content = "text"   
    Else
       ' i dunno what to use here as it is not the same as WinForms
    End If

What to do ?

OR

Please help me convert this c# code to WPF VB.NET

Label1.Invoke((MethodInvoker)delegate {
Label1.Text = i.ToString() + "Files Converted";});
Software Dev
  • 5,368
  • 5
  • 22
  • 45

1 Answers1

1

You should not update the user interface in the DoWork method.

Call ReportProgress in your DoWork method after each task is complete. Set the message you want displayed in the UserState parameter.

Then handle the ProgressChanged event in your Form, extract the message from e.UserState and use it to update your label.

Think of it as the Background worker sending a message by calling ReportProgress, and your main form receiving the message by handling ProgressChanged.

SSS
  • 4,807
  • 1
  • 23
  • 44
  • well, how am i supposed to use `ReportProgress` as i want to change the label text after each task is completed in `DoWork` event ? As i mentioned , my bgworker has many tasks and i want to change the label text after each task..how to do that ? – Software Dev Dec 19 '17 at 04:41
  • 3
    You call `ReportProgress` after each task is complete. The arguments are the progress percent and an arbitrary user state. You can pass anything, e.g. zero, for the percent and just ignore it in the `ProgressChanged` event handler. The user state can be anything. In your case, I'd suggest that you pass the text you want displayed in the `Label`. In the `ProgressChanged` event handler, you simply get that `String` and assign it to the `Text` of the `Label. – jmcilhinney Dec 19 '17 at 05:26
  • Check out my example [here](http://www.vbforums.com/showthread.php?471889-Using-the-BackgroundWorker-Component). You can see how `String` can be passed and used. Instead of a loop, you simply have multiple discrete calls to `ReportProgress` with different text each time. – jmcilhinney Dec 19 '17 at 05:28