c# add label from form2

做~自己de王妃 提交于 2019-11-28 13:05:20

问题


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


回答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);
}



回答2:


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();


来源:https://stackoverflow.com/questions/32916215/c-sharp-add-label-from-form2

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!