-3

Form2 code:

public void button2_Click(object sender, EventArgs e)
        {   
          Form1 form1form = new Form1();
            Label asd = new Label();
            asd.Text = "asdasasdasdasd";
            form1form.Controls.Add(asd);

            Form2 form2form = new Form2();
             form2form.close();

}

I want to add new label and button on form1 from form2

how it made ?

thanks

peace
  • 21
  • 7
  • 1
    First of all, you're not displaying `form1form` at any point; you're just creating a new instance of `Form2` and closing it (which won't compile because it needs to be `.Close()` not `.close()` :)) Secondly, why are you dynamically adding the controls? Design your form ahead of time, and display it on demand. – Arian Motamedi Oct 02 '15 at 21:42
  • I think to some degree they have designed the form ahead of time, based on the fact that the classes are called "Form1" and "Form2" instead of using the generic "Form" class. – Sophie Coyne Oct 02 '15 at 21:53
  • How did Form2 get displayed in the first place? Did Form1 make an instance of Form2 and show it? – Idle_Mind Oct 03 '15 at 03:22

2 Answers2

1

If you want to access form1form from form2form you must have public reference to form1form. Declare property in form1form like below:

public static form1form Instance { get; private set; }

Then set Instance in Load event of form1form:

private void form1form_Load(object sender, EventArgs e)
{
   Instance = this;
}

In form2form:

public void button2_Click(object sender, EventArgs e)
{
    Label asd = new Label();
    asd.Text = "asdasasdasdasd";
    form1form.Instance.Controls.Add(asd);
}
Paviel Kraskoŭski
  • 1,429
  • 9
  • 16
0

To add all controls in form2 to form1:

foreach(Control control in form2form.Controls)
{
    form1form.Controls.Add(control);
}

Or if you want to just add those two things, there are two options: 1. Make those two Controls public as so

public class Form2 : Form
{
    //othercode
    public Button button;
}

And then add these specific controls by:

form1form.Controls.Add(form2form.button);

2: Add them using the names, for example: say the name of the button is "button" and the name of the label is "label".

form1form.Controls.Add(form2form.Controls.Find("button",true).FirstOrDefault();
Sophie Coyne
  • 1,018
  • 7
  • 16
  • And please for the love of god *never* actually do this. This answer is almost right (you might run into issues adding controls already associated with another form), but you never would actually want to do it. – BradleyDotNET Oct 02 '15 at 21:45
  • @BradleyDotNET Yeah, I suppose. It's a strange answer to a strange request :p – Sophie Coyne Oct 02 '15 at 22:32