Abid Ali
Abid Ali

Reputation: 1747

Create and add a new control dynamically to a form

I have created a label using the following code:

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

I want to be able to create a new label and add it to my form when I click on this label. How can I do that?

Upvotes: 0

Views: 1237

Answers (2)

Hans Passant
Hans Passant

Reputation: 942338

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

You've made the label static, there is only one of them. Adding the same label to the Controls collection has no effect. You need to create a new Label control:

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
    //...
}

The intention of this code is hard to guess, I just wrote something that had visible side-effects.

Upvotes: 1

keyboardP
keyboardP

Reputation: 69372

You can add a click handler:

la.Click += new EventHandler(la_Click);

Then in the handler:

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

Edit - Explanation from comments. Your code would look like this:

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
}

Upvotes: 1

Related Questions