Link to home
Start Free TrialLog in
Avatar of spendergrass
spendergrass

asked on

C# WinForms - What order are controls added to control collection?

I have a C# WinFroms Application with the following code:

for (int i = 0; i < this.Controls.Count; i++)
  {
    if (this.Controls[i] is ListBox)
      {
         Control newCtrl = this.Controls[i];
         ListBox lb = (ListBox)newCtrl;
         lb.ClearSelected();
       }
  }

When I step through the code, the controls do not seem to be in any particular order within the collection.  In order for my code to work correctly, I need to clear certain listboxes, before clearing other listboxes.  Is there a way to designate what order the controls are put into the collection?

Thanks,
Sarah
Avatar of Mike Tomlinson
Mike Tomlinson
Flag of United States of America image

If you know the names before hand, then do something more along these lines:
       
        private void button1_Click(object sender, EventArgs e)
        {
            ListBox lb;
            lb = (ListBox)getControlByName(this, "listBox1");
            lb.ClearSelected();
            lb = (ListBox)getControlByName(this, "listBox2");
            lb.ClearSelected();
            lb = (ListBox)getControlByName(this, "listBox3");
            lb.ClearSelected();
        }

        private Control getControlByName(Control ctl, string ctlName)
        {
            foreach (Control child in ctl.Controls)
            {
                if (child.Name == ctlName)
                    return child;
                else if (child.HasChildren)
                {
                    Control retChild = getControlByName(child, ctlName);
                    if (retChild != null)
                        return retChild;
                }
            }
            return null;
        }

You can of course do more error checking than I did.  Make sure that null was not returned and the the returned control was actually a ListBox before casting it...
ASKER CERTIFIED SOLUTION
Avatar of RubenvdLinden
RubenvdLinden

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
But after seeing that...if you have a specific order and know the names, then why not just do it directly?

    listBox1.ClearSelected();
    listBox2.ClearSelected();
    listBox3.ClearSelected();
Hi
       you can set "Tag" for your listbox and with respect the tag name you can clear or do whatever you want.
Avatar of spendergrass
spendergrass

ASKER

I was hoping to be able to keep the code that I posted generic - not having to specify the order within that section of code.  Changing the order the controls are added to the form will allow me to do this.  Thanks everyone for your help!

Sarah