Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

InvokeRequired and ToolStripStatusLabel

In my application I have class that is responsible for all database actions. It is called from main class and uses delegates to call methods after action is complete. Because it is asynchronous I must use invoke on my GUI, so I've created a simple extensions method:

 public static void InvokeIfRequired<T>(this T c, Action<T> action)
            where T: Control
        {
            if (c.InvokeRequired)
            {
                c.Invoke(new Action(() => action(c)));
            }
            else
            {
                action(c);
            }
        }

This works fine when I try to call it on textBox:

textBox1.InvokeIfRequired(c => { c.Text = "it works!"; });

but when I try to call it on ToolStripStatusLabel or ToolStripProgressBar I get an error:

The type 'System.Windows.Forms.ToolStripStatusLabel' cannot be used as type parameter 'T' in the generic type or method 'SimpleApp.Helpers.InvokeIfRequired(T, System.Action)'. There is no implicit reference conversion from 'System.Windows.Forms.ToolStripStatusLabel' to 'System.Windows.Forms.Control'.

I know that this is probably a simple fix, but I just can handle it :/

like image 392
Misiu Avatar asked Sep 14 '12 06:09

Misiu


2 Answers

This is because ToolStripItem (base for those two causing an error) is a Component and not a Control. Try calling your extension method on the tool strip that owns them and adjust your delegate methods.

like image 87
slawekwin Avatar answered Sep 28 '22 07:09

slawekwin


I'd like to add up to the accepted solution. You can get the control from the component by using the GetCurrentParent method of the ToolStripStatusLabel.

Instead of doing toolStripStatusLabel1.InvokeIfRequired, do toolStripStatusLabel1.GetCurrentParent().InvokeIfRequired

like image 35
Mathter Avatar answered Sep 28 '22 06:09

Mathter