1

So it's obviously something simple but I'm losing too much time on this topic already. I have a very simple(as it should be in my opinion) method which task is to iterate through all buttons in my parent form.

Here it is:

public void SetForeColor(BaseForm frm, Form f)
{
    foreach (ToolStripButton button in frm.Controls.OfType<ToolStripButton>())
    {               
            MessageBox.Show("Soles clicked"+" "+f.Name.ToString());
    }

}

Where BaseForm frm is the argument that should take the MDIparent as value. I call this method from another one where I actually get the MDIparent :

 protected void LoadForm<T>(ToolStripButton formButton, string buttonText) where T : Form
        {
            MainForm frm = this.MdiParent as MainForm;
            if (frm == null) frm = this as MainForm;
            T sendTo;
....
            SetForeColor(frm, sendTo);

But I don't get any response. The LoadForm<T> function is working fine, so my suggestion is that I'm making mistake in the foreach but it seems so very straight forward to me...

Leron
  • 9,546
  • 35
  • 156
  • 257

4 Answers4

1

Chances are your buttons are not direct children of the form, but are contained in a ToolStrip component that is itself a child of the form.

Try something like:

foreach (ToolStrip toolStrip in frm.Controls.OfType<ToolStrip>()) {
    foreach (ToolStripButton button
             in toolStrip.Controls.OfType<ToolStripButton>()) {               
        MessageBox.Show("Soles clicked " + f.Name);
    }
}
Frédéric Hamidi
  • 258,201
  • 41
  • 486
  • 479
1

Assuming ToolStripButton is the standard button in the .net framework, your foreach loop will not execute as there will be no buttons of type ToolStripButton in the form's control collection.

ToolStripButtons have to be parented by a MenuStrip, ToolStrip or StatusStrip, so you would need to iterate any toolstrip's controls:

foreach (var strip in frm.Controls.OfType<ToolStrip>())
{
     foreach (var item in strip.Items)
     {
          MessageBox.Show("Soles clicked " + f.Name.ToString());
     }
}
Pondidum
  • 11,457
  • 8
  • 50
  • 69
0

You need to check whether the form is of the same type too:

foreach (Form frm in this.MdiChildren)
    {
        if (frm.GetType() == form.GetType() 
            && frm != form)
        {
            frm.Close();
        }
    }
0

Your foreach statement only searches the top layer of the controls collection.

foreach (ToolStripButton button in frm.Controls.OfType<ToolStripButton>()) {               
    MessageBox.Show("Soles clicked"+" "+f.Name.ToString());
}

While it is in fact a collection in a collection in a collection... etc. You need to search through the control collection and all its descendants.

The answer to this question has a method to retrieve all descendants.

Community
  • 1
  • 1
Maarten
  • 22,527
  • 3
  • 47
  • 68