如何控制来自另一个表单的表单加载

How to control form load from another form

我想从另一个表单控制我的表单加载事件。 我的问题 我在 form1 运行时创建了一些 winform control,但创建将由 form2.

控制

我将从 form2 中的用户读取一些数据,当用户输入特定文本时,我将在 form1 中创建 winform 控件。

我编写了一些代码来使用 from1 在运行时创建 winform 控件。

private TextBox txtBox = new TextBox();
        private Button btnAdd = new Button();
        private ListBox lstBox = new ListBox();
        private CheckBox chkBox = new CheckBox();
        private Label lblCount = new Label();
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            this.MaximizeBox = false;
            this.MinimizeBox = false;
            this.BackColor = Color.White;
            this.ForeColor = Color.Black;
            this.Size = new System.Drawing.Size(550, 550);
            this.Text = "Test Create form in runtime ";
            this.FormBorderStyle = FormBorderStyle.FixedDialog;
            this.StartPosition = FormStartPosition.CenterScreen;

            this.btnAdd.BackColor = Color.Gray;
            this.btnAdd.Text = "Add";
            this.btnAdd.Location = new System.Drawing.Point(90, 25);
            this.btnAdd.Size = new System.Drawing.Size(50, 25);
            this.txtBox.Text = "Text";
            this.txtBox.Location = new System.Drawing.Point(10, 25);
            this.txtBox.Size = new System.Drawing.Size(70, 20);

            this.lstBox.Items.Add("One");

            this.lstBox.Sorted = true;
            this.lstBox.Location = new System.Drawing.Point(10, 55);
            this.lstBox.Size = new System.Drawing.Size(130, 95);
            this.chkBox.Text = "Disable";
            this.chkBox.Location = new System.Drawing.Point(15, 190);
            this.chkBox.Size = new System.Drawing.Size(110, 30);
            this.lblCount.Text = lstBox.Items.Count.ToString() + " items";
            this.lblCount.Location = new System.Drawing.Point(55, 160);
            this.lblCount.Size = new System.Drawing.Size(65, 15);

            this.Controls.Add(btnAdd);
            this.Controls.Add(txtBox);
            this.Controls.Add(lstBox);
            this.Controls.Add(chkBox);
            this.Controls.Add(lblCount);

        }

如何从 form2 制作同样的东西?

不知道你需要哪种'Control'。然而在多表单环境中,表单之间的通信是微不足道的。交流的方式有很多种,其中一种可以是

在父表单中创建 public 类型 Form 的属性,

public Form propForm1 {get;set;}

在菜单项上单击时打开 form1,将其对象存储到 public 属性。

var form1 = New yourchildformname();
form1.MdiParent = this;
propForm1 = form1; // Add this line.
form1.Show();

现在每次单击其他按钮打开 form2 时,都会有 propForm1 对象,您可以使用该对象在该表单上设置一些数据。

编辑: 在 form2 上,您可以访问 form1 的控件,如

private void button1_Click(object sender, EventArgs e)
{
    this.parent.propForm1.txtUserName = "Yokohama";
}

记住上面的代码是在 form2 上的。同时将 txtUserName 的 'access modifier' 属性 从 private 设置为 public.