Link to home
Start Free TrialLog in
Avatar of purplesoup
purplesoupFlag for United Kingdom of Great Britain and Northern Ireland

asked on

Converting a Control to a ToolStripButton Object

I have a reference to a control that I know is of type ToolStripButton, but when I try to cast it to an object of type ToolStripButton I get a compiler error

Error      2      Cannot convert type 'System.Windows.Forms.Control' to 'System.Windows.Forms.ToolStripButton'      

Here is the code

    foreach (Control c in this.Controls)
            {
                if (c.GetType() == typeof(System.Windows.Forms.ToolStripButton))        
                {
                    ToolStripButton t = (System.Windows.Forms.ToolStripButton)c;
                    // ToolStripButton t = c as System.Windows.Forms.ToolStripButton;
                    SetToolstripButton(t);
                }                
            }
       
How can I do this?
Avatar of Nash2334
Nash2334

If it's passing the type check you should be able to cast it fine, where does the problem occur?
Note that you may need to recurse through the controls if you are calling this method from your base form; the form's control references are only to its direct children.

private void FindToolStripButton(Control.ControlCollection controlCollection)
        {
            foreach (Control control in controlCollection)
            {
                if (control.Controls.Count > 0)
                {
                        FindToolStripButton(control.Controls);
                }
                else
                {
                         if (control.GetType().Equals(typeof(ToolStripButton))
                         {
                                 ToolStripButton t = control as ToolStripButton;
                                 SetToolStripButton(t);
                         }
                }
ASKER CERTIFIED SOLUTION
Avatar of purplesoup
purplesoup
Flag of United Kingdom of Great Britain and Northern Ireland image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Closed, 500 points refunded.
Vee_Mod
Community Support Moderator