繁体   English   中英

C# 如何从 2nd Form 以 1st Form 创建 object

[英]C# how to create object in 1st Form from 2nd Form

我不清楚如何从第 2 形式在第 1 形式(主形式)中创建 object (属性:带有 label 和内部文本框的面板)。

  1. 第一种形式有一个面板,应在其中创建属性
  2. 第一种形式也有一个打开第二种形式的按钮
  3. 2nd Form 负责创建和配置属性
  4. 第二种形式有按钮- “创建”。 单击时,它应该在 1st Form 中创建一个属性并将其插入到Panel of Attributes中。

您能否提供一些示例如何执行此类操作?

主表格 第二种形式

为什么不让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.

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