C#中两个Form窗口之间的传值(父->子)(子->父)

首先定义两个Form,一个为Form1,一个为Form2,其中Form1作为父窗口,Form2作为子窗口

1、父窗口传值给子窗口

       Form1中代码:

        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            Form2 lForm = new Form2();//实例化一个Form2窗口
            lForm.String1 = "传值给子窗口Form2成功";//设置Form2中string1的值
            lForm.SetValue();//设置Form2中Label1的
            lForm.ShowDialog();
        }

       Form2中代码:

        private string string1;
        public string String1
        {
            set
            {
                string1 = value;
            }
        }

        public void SetValue()
        {
            this.label1.Text = string1;
        }

        public Form2()
        {
            InitializeComponent();
        }


2、子窗口返回值给父窗口


      Form1中代码:


        public Form1()
        {
            InitializeComponent();
        }


        private string strValue;
        public string StrValue
        {
            set
            {
                strValue = value;
            }
        }


        private void btnShowForm2_Click(object sender, EventArgs e)
        {
            Form2 lForm = new Form2();
            lForm.Owner = this;//重要的一步,主要是使Form2的Owner指针指向Form1
            lForm.ShowDialog();
            MessageBox.Show(strValue);//显示返回的值
        }


        From2中代码:


        public Form2()
        {
            InitializeComponent();
        }


        private void btnClose_Click(object sender, EventArgs e)
        {
            Form1 lForm1 = (Form1)this.Owner;//把Form2的父窗口指针赋给lForm1
            lForm1.StrValue = "子窗口Form2返回数值成功";//使用父窗口指针赋值
            this.Close();
        }

你可能感兴趣的:(C#中两个Form窗口之间的传值(父->子)(子->父))