Search code examples
c#winformsbackgroundworker

Backgroundworker progresschanged event c#


I am using background worker in winforms. In backgroundworker_progresschanged event e.userstate is a item which is to be added in the listbox. At the same time I want to show the e.userstate on the popup window.

Here is my code:

In backgroundworker_progresschanged event setlable() is a method which is from the another class.

 public void SetLable(string pbValue)
    {
        try
        {
            label1.Text = pbValue;

        }
        catch (Exception ex)
        { }
        label1.ForeColor = Color.Red;
    }

I want to add userstate in listbox2 and at the same time want to show that on popup window which i have created in another form. I have comment out the listbox.items.add because both are not working at the same time.

private void backgroundWorker2_DoWork(object sender, DoWorkEventArgs e)
    {
        List<string> result1 = new List<string>();

        var found = obj.getFiles();

        foreach (var item in found)
        {
            if (item.Contains("ERROR"))
            {
                result1.Add(item);

                (sender as BackgroundWorker).ReportProgress(0, item);

            }
            else
                (sender as BackgroundWorker).ReportProgress(0);
            System.Threading.Thread.Sleep(500);

        }
        e.Result = result1;
    }

    private void backgroundWorker2_ProgressChanged(object sender, ProgressChangedEventArgs e)
    {
        if (e.UserState != null)
            pop.SetLable(e.UserState.ToString());
       // listBox2.Items.Add(e.UserState);

    }

I want both to be work at same time.

   pop.SetLable(e.UserState.ToString());
// listBox2.Items.Add(e.UserState);

Is this possible?


Solution

  • An if statement only executes the statement immediately following it. If you intend for more than one thing to occur, use a block:

    private void backgroundWorker2_ProgressChanged(object sender, ProgressChangedEventArgs e)
    {
        if (e.UserState != null)
        {
            pop.SetLable(e.UserState.ToString());
            listBox2.Items.Add(e.UserState.ToString());
        }
    }
    

    Get into the habit of immediately typing both brackets in when you create every single if statement (same goes for any else portions!). Even single statements should be enclosed in a block for if/else statements...that way you can add things to your logic later and not fall into this type of subtle bug.