30

在 Windows 窗体中,我可以通过执行以下操作动态添加控件:

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);
}

如何在 中动态添加控件FlowLayoutPanel

4

2 回答 2

46

对于FlowLayoutPanel,您不需要指定 a.Location因为控件是为您安排的:

表示动态水平或垂直布置其内容的面板。... FlowLayoutPanel 控件以水平或垂直流动方向排列其内容。它的内容可以从一行到下一行,或者从一列到下一列。

只需将“ flowLayoutPanel1”更改为您的名称FlowLayoutPanel

for (int i = 0; i < 5; i++)
{
    Button button = new Button();
    button.Tag = i;
    flowLayoutPanel1.Controls.Add(button);
}
于 2013-06-03T18:44:56.090 回答
0

使项目从数据库(sql server)动态流向 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);                

        }
于 2014-10-09T12:16:15.297 回答