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.
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 ?
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
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();
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.