通过在运行时单击按钮创建控件c#

时间:2015-06-08 11:24:39

标签: c#

我在点击按钮时尝试在运行时添加标签, 这是我的代码,但当你点击按钮时,只需在新位置添加新标签,然后点击该按钮即可显示之前制作的标签 我想在点击按钮后逐一显示所有这些内容 我该如何解决?

Label lbl;
int number;
int locationX = 2;
int locationY = 4;

public void CreateRuntimeControl(PictureBox pic)
{
    lbl; = new Label();
    number++;
    locationX++;
    locationY++;
    lbl.Name = "lbl" + number.ToString();
    lbl.Size = new System.Drawing.Size(100, 50);
    lbl.Location = new System.Drawing.Point(10 + locationX, 10 + locationY);
    lbl.Text = number.ToString();
    lbl.BackColor = Color.Gray;
    pic.Controls.Add(lbl);
}

最好的问候

3 个答案:

答案 0 :(得分:0)

你应该移动lbl = new Label();声明到CreateRuntimeControl()函数的主体,否则你重新使用相同的标签,只是移动它而不是创建新标签

答案 1 :(得分:0)

尝试:

int number;
int locationX = 2;
int locationY = 4;

public void CreateRuntimeControl(PictureBox pic)
{
    Label lbl = new Label();
    number++;
    locationX++;
    locationY++;
    lbl.Name = "lbl" + number.ToString();
    lbl.Size = new System.Drawing.Size(100, 50);
    lbl.Location = new System.Drawing.Point(10 + locationX, 10 + locationY);
    lbl.Text = number.ToString();
    lbl.BackColor = Color.Gray;
    pic.Controls.Add(lbl);
}

答案 2 :(得分:0)

*************** ************************************************** *************我找到了答案,我想把它放到这里,如果有其他人有我的问题找到这个页面并解决问题

        int number;
    int locationX;
    int locationY;

    public void CreateRuntimeControl(PictureBox pic)
    {
        Label lbl = new Label();
        number++;
        locationX++;
        locationY = locationY + 100;
        lbl.Name = "lbl" + number.ToString();
        lbl.Size = new System.Drawing.Size(100, 50);
        lbl.Location = new System.Drawing.Point(10 + locationX, 10 + locationY);
        lbl.Text = number.ToString();
        lbl.BackColor = Color.Gray;
        pic.Controls.Add(lbl);
    }

最好的问候