How can I loop thru all controls (including ToolStripItems) C#

Posted by Murray on Stack Overflow See other posts from Stack Overflow or by Murray
Published on 2010-12-22T04:55:18Z Indexed on 2010/12/22 5:54 UTC
Read the original article Hit count: 322

Filed under:
|

I need to save and restore settings for specific controls on a form.

I loop thru all controls and return the one whose name matches the one I want, like so:

private static Control GetControlByName(string name, Control.ControlCollection Controls)
{
  Control thisControl = null;
  foreach (Control c in Controls)
  {
    if (c.Name == name)
    {
      thisControl = c;
      break;
    }
    if (c.Controls.Count > 0)
    {
        thisControl = GetControlByName(name, c.Controls);
      if (thisControl != null)
      {
        break;
      }
    }
  }
  return thisControl;
}

From this I can determine the type of control and therefore the property that should be / has been stored.

This works well unless the control is one of the ToolStrip family which has been added to a toolstrip. e.g.

this.toolStrip.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
        this.lblUsername,  // ToolStripLabel 
        this.toolStripSeparator1,
        this.cbxCompany}); // ToolStripComboBox 

In this case I can see the control I'm interested in (cbxCompany) when debugging, but the name property has no value so the code does not match to it.

Any suggestions on how I can get to these controls too?

Cheers, Murray

© Stack Overflow or respective owner

Related posts about c#

Related posts about controls