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

后端 未结 5 1497
北海茫月
北海茫月 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:59

    What if in future some other designer removed the controls, added back etc? Checking the designer always is a mess. What would be better is to sort the controls in the container control before you enumerate. I use this extension method (if you have Linq):

    public static List ToControlsSorted(this Control panel)
    {
        var controls = panel.Controls.OfType().ToList();
        controls.Sort((c1, c2) => c1.TabIndex.CompareTo(c2.TabIndex));
        return controls;
    }
    

    And you can:

    foreach (FlowLayoutPanel aDaysControl in this.ToControlsSorted())
    {
        MessageBox.Show(aDaysControl.TabIndex.ToString());
    }
    

    (Above is for TabIndex). Would be trivial to sort according to Tag from that.

提交回复
热议问题