Flowlayout 在控件之间动态添加控件

Flowlayout Adding control in between controls dynamically

我正在对现有应用程序进行更改。我遇到了一个问题,我需要在流程面板的中间添加控件。我已经简化了下面的问题。

为每个对象添加一个标签和按钮控件。我在初始屏幕启动时添加了 3 组对象。

当用户单击任何按钮时,会添加另一个对象:

但是,我需要将控件放在单击它的按钮下方,而不是添加在底部。例如,单击 A 按钮,然后标签 D 和按钮 d 应出现在 A 按钮下方,并向下移动其他控件。该事件是一个按钮,但也可以是其他事件,例如下拉菜单,但 rules/behaviour 是相同的。是否可以在流面板中间添加一个控件?

下面是代码示例:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace WindowsFormsApp8
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            List<Control_Info> list = new List<Control_Info>();
            list.Add(new Control_Info { Label_Name = "Test A", Button_Name = "Desc A" });
            list.Add(new Control_Info { Label_Name = "Test B", Button_Name = "Desc B" });
            list.Add(new Control_Info { Label_Name = "Test C", Button_Name = "Desc C" });

            foreach (Control_Info ci in list)
            {
                loadControlToPanel(ci);
            }

        }

        private void loadControlToPanel(Control_Info ci)
        {
            Label label = new Label();
            label.Text = ci.Label_Name;
            label.AutoSize = false;
            flowLayoutPanel1.Controls.Add(label);

            Button button = new Button();
            button.Text = ci.Button_Name;
            button.AutoSize = false;
            button.Click += new EventHandler(buttonClickEvent);
            flowLayoutPanel1.Controls.Add(button);
        }

        private void buttonClickEvent(object sender, EventArgs e)
        {
            Control_Info ci = new Control_Info{ Label_Name = "Test D", Button_Name = "Desc D" };
            loadControlToPanel(ci);
        }
    }
}

使用SetChildIndex(...);方法,例如:

    Form f5 = new Form();
    FlowLayoutPanel panel = new FlowLayoutPanel { FlowDirection = FlowDirection.TopDown, Dock = DockStyle.Fill };
    f5.Controls.Add(panel);
    Label lbA = new Label { Text = "A" };
    Button btnA = new Button { Text = "A" };
    panel.Controls.Add(lbA);
    panel.Controls.Add(btnA);
    char c = 'B';
    EventHandler action = null; 
    action = (o, e) => {
        int index = panel.Controls.IndexOf((Control) o); // index of button clicked
        Label lbNew = new Label { Text = c.ToString() };
        Button btnNew = new Button { Text = c.ToString() };
        btnNew.Click += action;
        c++;
        panel.SuspendLayout();
        panel.Controls.Add(lbNew);
        panel.Controls.Add(btnNew);
        panel.Controls.SetChildIndex(btnNew, index+1);
        panel.Controls.SetChildIndex(lbNew, index+1);   
        panel.ResumeLayout(true);
    };
    btnA.Click += action;

    Application.Run(f5);