[英]How can I create a DataGridView in a TabPage of 2nd from by clicking the button in the 1st Form
[英]C# how to create object in 1st Form from 2nd Form
為什么不讓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();
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.