In a windows form, I can add control dynamically by doing this:

for (int i = 0; i < 5; i++)
{
    Button button = new Button();
    button.Location = new Point(160, 30 * i + 10);

    button.Tag = i;
    this.Controls.Add(button);
}

How do I add controls dynamically in a FlowLayoutPanel?

有帮助吗?

解决方案

For a FlowLayoutPanel, you don't need to specify a .Location since the controls are arranged for you:

Represents a panel that dynamically lays out its contents horizontally or vertically. ... The FlowLayoutPanel control arranges its contents in a horizontal or vertical flow direction. Its contents can be wrapped from one row to the next, or from one column to the next.

Just change "flowLayoutPanel1" to the name of your FlowLayoutPanel:

for (int i = 0; i < 5; i++)
{
    Button button = new Button();
    button.Tag = i;
    flowLayoutPanel1.Controls.Add(button);
}

其他提示

Make items flow dynamically from database(sql server) to flowLayoutPanel1 :

 void button1_Enter(object sender, EventArgs e)
    {
        Button btn = sender as Button;
        btn.BackColor = Color.Gold;
    }

void button1_Leave(object sender, EventArgs e)
    {
        Button btn = sender as Button;
        btn.BackColor = Color.Green;
    }


private void form1_Load(object sender, EventArgs e)
    {
        flowLayoutPanel1.Controls.Clear();
        SqlConnection cn = new SqlConnection(@"server=.;database=MyDatabase;integrated security=true");

        SqlDataAdapter da = new SqlDataAdapter("select * from Items order by ItemsName", cn);

        DataTable dt = new DataTable();
        da.Fill(dt);

        for (int i = 0; i < dt.Rows.Count; i++)
        {
            Button btn = new Button();
            btn.Name = "btn" + dt.Rows[i][1];
            btn.Tag = dt.Rows[i][1];
            btn.Text = dt.Rows[i][2].ToString();
            btn.Font = new Font("Arial", 14f, FontStyle.Bold);
            // btn.UseCompatibleTextRendering = true;
            btn.BackColor = Color.Green;
            btn.Height = 57;
            btn.Width = 116;
            btn.Click += button1_Click;   //  set any method
            btn.Enter += button1_Enter;   // 
            btn.Leave += button1_Leave;   //


            flowLayoutPanel1.Controls.Add(btn);                

        }
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top