yo3hcv
yo3hcv

Reputation: 1669

C# Toolstrip's progressbar and Label not updated from cross thread operations

For some reason, ToolStrip's ProgressBar and Label are not updated from other thread. After a lot of reading, I came up with this, but still not working (button is OK however, but is not on status bar).

    public void GdmReaderMessageEvent(object sender, GdmMessagesEventArgs e)
    {
        Console.WriteLine(e.Message);

        // error or abort
        if (e.Message.StartsWith("Error:") || e.Message.StartsWith("Aborted"))
        {

            // cross thread crap
            if (pb.GetCurrentParent().InvokeRequired)
                pb.GetCurrentParent().Invoke(new MethodInvoker(delegate { pb.Visible = false; }));

            if (lblStatus.GetCurrentParent().InvokeRequired)
                lblStatus.GetCurrentParent().Invoke(new MethodInvoker(delegate { lblStatus.Text = e.Message; }));

            btnImport.Invoke(new MethodInvoker(delegate { btnImport.Text = "Import"; }));

            //lblStatus.Text = e.Message;
            //btnImport.Text = "Import";
            //pb.Visible = false;
        }
    }

Edited, all function now, but this is just a callback from a BGW thread, I thought it's already obvious. If I use just that:

        lblStatus.Text = e.Message;  // this is a Label inside Status
        btnImport.Text = "Import";   // this is just a button on Form
        pb.Visible = false;          // this is a Progress Bar inside Status    

Cross thread error will be thrown. So that's why I used with Invoke(). Now the button CAN BE updated, but all controls from Status Bar not.

Hope is more clear now.

I use .NET 3.5, VS2008, Winforms. Any solution?

Upvotes: 1

Views: 1311

Answers (1)

yo3hcv
yo3hcv

Reputation: 1669

Ok , I found it. @Fixation, thanks for guide me with "this" (I mean Form itself). I was trying to use invoke of control which not worked.

Also, this post was useful unable to update progress bar with threading in C#

        this.BeginInvoke((Action)(() => pb.Visible = false));
        this.BeginInvoke((Action)(() => lblStatus.Text = e.Message));

Just perfect, thanks.

Upvotes: 0

Related Questions