Home > Software design >  Create a new label if button from second form is pressed
Create a new label if button from second form is pressed

Time:08-06

I'm making a program that supposed to create a label on the second form when a button from that second form is pressed, I successfully added the button on the second form now that I'm struggling with making the label to be added into the second form when that button is pressed because I don't know how to do that, this is my code:

void Button1Click(object sender, EventArgs e)
{
    Form form2 = new Form();
    form2.Size = new Size(350,350);
    
    // Setup
    Button finish = new Button();
    finish.Text = "Finish";
    
    finish.Location = new Point(x,100);
    
    // Utilize
    form2.Controls.Add(finish);
    
    form2.Text = "Second Form";
    form2.Show();
}

I have done googling and searching through stackoverflow ended up with no solution.

CodePudding user response:

This works in my small Windows Forms sample:

Form form2 = new Form();
form2.Size = new Size(350, 350);

// Setup
Button finish = new Button();
finish.Text = "Finish";

finish.Location = new Point(100, 100);
finish.Click  = (s, e) =>
{
    Label label = new Label();
    label.Text = "Finish was clicked";
    label.Location = new Point(10, 10);
    label.Width = 300;
    form2.Controls.Add(label);
};

// Utilize
form2.Controls.Add(finish);

form2.Text = "Second Form";
form2.Show();
  • Related