How can I get through all the controls (including ToolStripItems) C #

I need to save and restore settings for certain controls on the form.

I loop through all the controls and return the one whose name matches the one I want, for example:

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 saved.

This works well if the control is not one of the ToolStrip family that has been added to the toolbar. eg.

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 that interests me (cbxCompany) during debugging, but the name property does not matter, so the code does not match it.

Any suggestions on how I can get to these controls?

Cheers, Murray

+3
2

.

Pinichi , toolStrip.Controls - toolStrip.Items

:

private static Control GetControlByName(string controlName, Control.ControlCollection parent)
{
  Control c = null;
  foreach (Control ctrl in parent)
  {
    if (ctrl.Name.Equals(controlName))
    {
      c = ctrl;
      return c;
    }

    if (ctrl.GetType() == typeof(ToolStrip))
    {
      foreach (ToolStripItem item in ((ToolStrip)ctrl).Items)
      {
        if (item.Name.Equals(controlName))
        {
          switch (item.GetType().Name)
          {
            case "ToolStripComboBox":
              c = ((ToolStripComboBox)item).Control;
              break;
            case "ToolStripTextBox":
              c = ((ToolStripTextBox)item).Control;
              break;
          }
          if (c != null)
          {
            break;
          }
        }
      }
    }
    if (c == null)
      c = GetControlByName(controlName, ctrl.Controls);
    else
      break;
  }
  return c;
}
+3

:

//for toolstrip
            if (ctrl is ToolStrip)
            {
                ToolStrip ts = ctrl as ToolStrip;
                foreach (ToolStripItem it in ts.Items)
                {
                    if (it is ToolStrienter code herepSeparator)
                    {
                        //-------------------------
                    }
                    else
                    {
                        //do something
                    }

                }
            }//---------------
0

Source: https://habr.com/ru/post/1781582/


All Articles