InvokeRequired and ToolStripStatusLabel

Misiu picture Misiu · Sep 14, 2012 · Viewed 8.6k times · Source

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 :/

Answer

slawekwin picture slawekwin · Sep 14, 2012

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.