繁体   English   中英

在 flowlayoutpanel 中动态添加控件

[英]Add controls dynamically in flowlayoutpanel

在 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动态添加控件?

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

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

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

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

使项目从数据库(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);                

        }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM