如何将子窗体的值传给父窗体

   最近做项目的时候,想着menustrip里面的某一项,弹出对话框,对话框里有确定取消按钮,点击确定,将子窗体的值给窗体,点击取消,什么都不做。

   总共有3个窗体:form1,form2,form3,具体控件如下:




我的思路是利用类的字段属性来实现传值。代码如下

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace WindowsFormsApplication1
{
    public partial class Form3 : Form
    {
        public Form3()
        {
            InitializeComponent();
        }
        public string property
        {
            get;
            set;
        }
        private void button1_Click(object sender, EventArgs e)
        {
            property = textBox1.Text;
            this.Hide();
        }
    }
}


form2:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace WindowsFormsApplication1
{
    public partial class Form2 : Form
    {
        private string tome;
        public string tiem
        {
            get { return tome; }
            set { tome = value; }
        }
        public Form2()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            Form3 f3 = new Form3();
            f3.ShowDialog();
            this.tiem = f3.property;
            this.Hide();
        }
    }   
}


form1:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            Form2 f2 = new Form2();
            f2.ShowDialog();
            textBox1.Text = f2.tiem;
        }
    }
}

结果:




猜你喜欢

转载自blog.csdn.net/qq_37947654/article/details/70314472