如何以编程方式将控件添加到窗体?

时间:2010-08-02 01:40:09

标签: winforms c#-3.0

我正在尝试在面板中添加控件(Label)。 请参阅代码:

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 AddControlProgramatically
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            Label lbl = new Label();

            for (int x = 0; x <= 3; x++)
            {
                //create new label location after each loop
                //by multiplying the new value of variable x by 5, so the new label 
                //control will not overlap each other.
                lbl.Location = new System.Drawing.Point(52 + (x * 5), 58 + (x * 5));
                //create new id and text of the label
                lbl.Name = "label_" + x.ToString();
                lbl.Text = "Label " + x.ToString();

                this.panel1.Controls.Add(lbl);
            }
        }
    }
}

screenshot

这是表格。我想要完成的是以编程方式生成3个不同的控制标签。但正如您所看到的,它只显示最后一个。请帮我解决这个问题。我知道我的代码有问题(因为它不起作用)。谢谢......

4 个答案:

答案 0 :(得分:5)

Label lbl = new Label();放入循环中。

并使偏移更大,改变这个......

 lbl.Location = new System.Drawing.Point(52 + (x * 5), 58 + (x * 5))

...为:

lbl.Location = new System.Drawing.Point(52 + (x * 30), 58 + (x * 30))

答案 1 :(得分:2)

您需要在每次循环迭代中创建一个新标签。现在你只创建一个标签。

private void button1_Click(object sender, EventArgs e)
{
    for (int x = 0; x <= 3; x++)
    {
        Label lbl = new Label();

        //create new label location after each loop
        //by multiplying the new value of variable x by 5, so the new label 
        //control will not overlap each other.
        lbl.Location = new System.Drawing.Point(52 + (x * 5), 58 + (x * 5));
        //create new id and text of the label
        lbl.Name = "label_" + x.ToString();
        lbl.Text = "Label " + x.ToString();

        this.panel1.Controls.Add(lbl);
    }
}

答案 2 :(得分:0)

您需要将Label lbl = new Label();放入for循环中。

答案 3 :(得分:0)

这个问题很老,但是显然没有人花时间把它弄对。 您继续覆盖相同的Label对象实例。而是创建一个Label实例列表,然后将它们添加到您的表单中,如下所示:

        List < Label > myLabels = new List<Label>();
        for (int i = 0; i < 5; i++)
        {
            Label lbl = new Label();                
            //create new id and text of the label
            lbl.Name = "label_" + i.ToString();
            lbl.Text = "Label " + i.ToString();
            lbl.Width = 50;
            lbl.Location = new System.Drawing.Point(52 + (i * lbl.Width), 50);
            myLabels.Add(lbl);
        }
        foreach (Label l in myLabels)
        {
            this.Controls.Add(l);
        }