0

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.

  • 4
    Is this Windows Forms? You can add another Form to the project instead of creating it dynamically; place the label on the form, but make it invisible at first. Usually it's easier to make it visible later on instead of having to deal with dynamically created forms. – Markus Aug 05 '22 at 08:43

1 Answers1

1

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();
Gec
  • 428
  • 2
  • 10
  • Ok your code works but I'm a novice and I quite don't understand what the `(s,e)` does and why it have to be there?. – Pythonic User Aug 05 '22 at 12:04
  • 1
    You need to tell the program what to do when the button is clicked. In your code you have `void Button1Click(object sender, EventArgs e)` and some code inside. In the designer generated code, there is a line similar to `this.button1.Click += new System.EventHandler(this.button1_Click);` which tells it to run that function when the button is clicked. Here we do the same, using a `lambda expression` . See https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/operators/lambda-expressions and https://stackoverflow.com/questions/2465040/using-lambda-expressions-for-event-handlers – Gec Aug 05 '22 at 14:32
  • 1
    `(s, e)` is just short for `(object sender, EventArgs e)` -- C# will figure out the correct types and we don't need to worry about their names much, since we do not use them in code. We might as well have used the discard `_` and written `finish.Click += (_, _) => {...}` and it would have worked just the same. See https://learn.microsoft.com/en-us/dotnet/csharp/fundamentals/functional/discards for discards. – Gec Aug 05 '22 at 14:37