动态创建并向表单添加新控件

时间:2011-07-09 14:19:35

标签: winforms c#-4.0

我使用以下代码创建了一个标签:

public static System.Windows.Forms.PictureBox pc = new PictureBox(); 

public static System.Windows.Forms.Label la = new Label();

private void label2_Click(object sender, EventArgs e)
{
    label2.Visible = false;
    pictureBox2.Hide();
    Controls.Add(la);
    la.Location = new Point(78, 191);
    la.Size = new Size(72, 77);
    la.Image = _2WaySMSGatewayApp.Properties.Resources.message;
}

我希望能够在点击此标签时创建新标签并将其添加到我的表单中。我怎么能这样做?

2 个答案:

答案 0 :(得分:1)

您可以添加点击处理程序:

la.Click += new EventHandler(la_Click);

然后在处理程序中:

void la_Click(object sender, EventArgs e)
{
    //add new label
}

编辑 - 评论解释。你的代码看起来像这样:

public static System.Windows.Forms.PictureBox pc = new PictureBox(); 

public static System.Windows.Forms.Label la = new Label();

private void label2_Click(object sender, EventArgs e)
{
    label2.Visible = false;
    pictureBox2.Hide();
    Controls.Add(la);
    la.Location = new Point(78, 191);
    la.Size = new Size(72, 77);
    la.Image = _2WaySMSGatewayApp.Properties.Resources.message;
    la.Click += new EventHandler(la_Click);
}

void la_Click(object sender, EventArgs e)
{
    //the new label has been clicked
}

答案 1 :(得分:1)

 public static System.Windows.Forms.Label la = new Label();

您已将标签设为静态,只有其中一个。将相同的标签添加到Controls集合中无效。您需要创建一个新的Label控件:

private int labelCount;

private void label2_Click(object sender, EventArgs e)
{
    var la = new Label();
    la.Size = new Size(72, 77);
    la.Location = new Point(78, 191 + labelCount * (la.Height + 10));
    la.Image = _2WaySMSGatewayApp.Properties.Resources.message;
    la.Text = "Make it visible";
    labelCount++;
    la.Name = "label" + labelCount.ToString();
    la.Click += new EventHandler(la_Click);
    Controls.Add(la);
}

void la_Click(object sender, EventArgs e)
{
    var la = (Label)sender;
    // You could use the Name property
    //...
}

这段代码的意图很难猜测,我只是写了一些有明显副作用的东西。