Order of controls in a form's Control property in C#

后端 未结 5 1487
北海茫月
北海茫月 2021-01-18 19:35

I am having a peculiar problem with the order in which FlowLayoutPanels are added in to the form\'s controls property. This is what I tried,

I added

5条回答
  •  庸人自扰
    2021-01-18 19:52

    Is it really a problem?

    As long as the UI operates correctly (in terms of tab order, for example), I'd recommend that you don't make any assumptions about the order in which they're enumerated.

    EDIT: Thanks for explaining your requirement in more detail. I think I'd still recommend against using the order that they're stored in the Controls collection. It's always best to consider these implementation details to be 'opaque'. You have a tag associated with each control, so you can use this to identify the correct control. In order to speed up the processing, you could build a 7-element array that references the controls by ordinal:

    FlowLayoutPanel[] panels = new FlowLayoutPanel[7];
    
    foreach(FlowLayoutPanel panel in this.Controls)
    {
        panels[(int)panel.Tag] = panel;
    }
    
    // Now, you can reference the panels directly by subscript:
    
    panels[2].BackColor = Color.Aquamarine;
    

    Though I'd put some type-checking in to make this code a bit more robust!

提交回复
热议问题