简体   繁体   中英

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM