Почему бы не позволить 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
}
Сделав 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();
}