简体   繁体   中英

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.

  1. 1st Form has a panel in which Attribute should be created.
  2. 1st Form also has a Button which opens the 2nd Form.
  3. 2nd Form takes roles of creation & configuration of Attribute
  4. 2nd Form has Button -"Create". When clicked it should create an attribute in the 1st Form and insert it into Panel of Attributes .

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM