【问题标题】:C# how to create object in 1st Form from 2nd FormC#如何从第二种形式创建第一种形式的对象
【发布时间】:2020-07-27 00:57:23
【问题描述】:

我不清楚如何在 2nd Form 的 1st Form(主窗体)中创建一个对象 (属性:带有标签和文本框的面板)

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

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

【问题讨论】:

    标签: c# winforms controls


    【解决方案1】:

    为什么不让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(); 
      }
    

    【讨论】:

    • 或者.ShowDialog(this),然后((Form1)this.Owner).CreateMyControl();,可能会传递一些参数,这似乎是OP所追求的。
    猜你喜欢
    • 2014-06-01
    • 1970-01-01
    • 1970-01-01
    • 2011-07-20
    • 1970-01-01
    • 2016-01-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多