C# 在 flowlayoutpanel 中动态添加控件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16900522/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 08:05:53  来源:igfitidea点击:

Add controls dynamically in flowlayoutpanel

c#winformsdynamic-controlsflowlayoutpanel

提问by Karlx Swanovski

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

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

How do I add controls dynamically in a FlowLayoutPanel?

如何在 a 中动态添加控件FlowLayoutPanel

采纳答案by Idle_Mind

For a FlowLayoutPanel, you don't need to specify a location since the controls are arranged for you. Just change "flowLayoutPanel1" to the name of your FlowLayoutPanel:

对于 a FlowLayoutPanel,您无需指定位置,因为已为您安排了控件。只需将“ flowLayoutPanel1”更改为您的名称FlowLayoutPanel

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

回答by Sherif Hamdy

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

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

        }