[英]C# how to create object in 1st Form from 2nd Form
I'm not clear how to create an object (Attribute: panel with label and text box inside) in the 1st Form (Main form) from 2nd Form.我不清楚如何从第 2 形式在第 1 形式(主形式)中创建 object (属性:带有 label 和内部文本框的面板)。
Could you please provide me with some examples how It would be possible to perform such action?您能否提供一些示例如何执行此类操作?
Why not let Form1
create the control for itself ?为什么不让Form1
自己创建控件呢?
public partial class Form1 : Form {
public void CreateMyControl() {
Panel attrPanel = new Panel() {
Parent = this,
Size = new Size(100, 60), //TODO: Put the right value here
Location = new Point(0, 0), //TODO: Put the right value here
};
new Label() {
Parent = attrPanel,
Text = "I'm the Label", //TODO: Put the right value here
Location = new Point(4, 4) //TODO: Put the right value here
};
new TextBox() {
Parent = attrPanel,
Text = "I'm the TextBox", //TODO: Put the right value here
Location = new Point(4, 34) //TODO: Put the right value here
}
}
private void btnRun_Click(object sender, EventArgs e) {
// We create Form2 instance and pass current Form1 instance to it
Form2 form2 = new Form2(this);
form2.ShowDialog(); // Or Show
}
Having done with Form1
, let's pass Form1
to via constructor完成Form1
后,让我们通过构造函数将Form1
传递给
public partial class Form2 : Form {
...
public Form1 ParentForm {get;} = null;
public Form2() {
InitializeComponent();
}
public Form2(Form1 parentForm) : this() {
ParentForm = parentForm;
}
private void btnCreateControl_Click(object sender, EventArgs e) {
// If we have parent form, create some controls on it
if (ParentForm != null)
ParentForm.CreateMyControl();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.