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

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

    if you look at the code generated by the designer Form1.designer.cs it will look something like this:

            // 
            // Form1
            // 
            this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
            this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
            this.ClientSize = new System.Drawing.Size(658, 160);
            this.Controls.Add(this.flowLayoutPanel7);
            this.Controls.Add(this.flowLayoutPanel6);
            this.Controls.Add(this.flowLayoutPanel5);
            this.Controls.Add(this.flowLayoutPanel4);
            this.Controls.Add(this.flowLayoutPanel3);
            this.Controls.Add(this.flowLayoutPanel2);
            this.Controls.Add(this.flowLayoutPanel1);
            this.Name = "Form1";
            this.Text = "Form1";
            this.ResumeLayout(false);
    

    note how it was built up you added panel 1 first then 2 etc. but as the code runs through it will add 7 first then 6.

    this code will be in the InitializeComponent() function generated by the designer.

    Why do you need them to run in a certain order?

    I wouldn't rely on the designer to keep the order you want.. i would sort the controls my self:

            var flowpanelinOrder = from n in this.Controls.Cast()
                                   where n is FlowLayoutPanel
                                   orderby int.Parse(n.Tag.ToString())
                                   select n;
    
            /* non linq
            List flowpanelinOrder = new List();
            foreach (Control c in this.Controls)
            {
                if (c is FlowLayoutPanel) flowpanelinOrder.Add(c);                
            }
            flowpanelinOrder.Sort();
             * */
    
            foreach (FlowLayoutPanel aDaysControl in flowpanelinOrder)
            {
                MessageBox.Show(aDaysControl.Tag.ToString());
            }
    

提交回复
热议问题