[英]c# add label from form2
Form2 code:表格2代码:
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我想从 form2 在 form1 上添加新标签和按钮
how it made ?它是怎么做的?
thanks谢谢
If you want to access form1form
from form2form
you must have public reference to form1form
.如果你想从
form2form
访问form1form
你必须有对form1form
公共引用。 Declare property in form1form
like below:在
form1form
声明属性,如下所示:
public static form1form Instance { get; private set; }
Then set Instance
in Load
event of form1form
:然后在
form1form
Load
事件中设置Instance
:
private void form1form_Load(object sender, EventArgs e)
{
Instance = this;
}
In form2form
:在
form2form
:
public void button2_Click(object sender, EventArgs e)
{
Label asd = new Label();
asd.Text = "asdasasdasdasd";
form1form.Instance.Controls.Add(asd);
}
To add all controls in form2 to form1:要将 form2 中的所有控件添加到 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或者,如果您只想添加这两件事,则有两种选择: 1. 将这两个控件设为公开
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". 2:使用名称添加它们,例如:说按钮的名称是“按钮”,标签的名称是“标签”。
form1form.Controls.Add(form2form.Controls.Find("button",true).FirstOrDefault();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.