如何从另一种形式控制表单加载

时间:2015-09-03 07:58:01

标签: c# winforms windows-applications

我想从另一个表单控制表单加载事件。 我的问题我在winform control运行时创建了一些form1,但创建将由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做同样的事情?

1 个答案:

答案 0 :(得分:2)

我不知道哪种'控制'你需要。然而,在多种形式的环境中,表单之间的通信是微不足道的。有很多方法可以进行沟通,例如可以像

那样进行沟通

在“父表单”中创建Form类型的公共属性,

public Form propForm1 {get;set;}

当点击菜单项时,你打开form1,将它的对象存储到该公共财产。

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的属性从privatepublic