欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

实现子窗口到主窗口的传值 博客分类: C# C#窗口窗口间传值 

程序员文章站 2024-03-25 18:21:10
...

在子窗口的两个textbox输入字符串后,他们的内容将会显示在主窗口的textbox上。


子窗口的控件:两个textbox,两个button

子窗口:

 

 

namespace sign_in
{
    public partial class Child : Form
    {
        private string c_no;
        private string c_name;
        
        public string c_No
        {
            get
            {
                return this.c_no;
            }
            set
            {
                this.c_no = value;
            }
        }

        public string c_Name
        {
            get
            {
                return this.c_name;
            }
            set
            {
                this.c_name = value;
            }
        }

        private MainForm mainform;    //创建一个主窗口对象

        public child()
        {
            InitializeComponent();
        }

        private void Child_Load(object sender, EventArgs e)
        {
            mainform = (MainForm)this.Owner;     //窗口间传值keypoint
        }

        private void button1_Click(object sender, EventArgs e)
        {
            this.no = this.textBox1.Text;
            this.name = this.textBox2.Text;
            this.DialogResult = DialogResult.OK;
            this.Close();
        }

        private void button2_Click(object sender, EventArgs e)
        {
            this.Dispose();
        }
    }
}

 

 

 

主窗口控件:两个textbox,一个button

主窗口:

 

 

namespace sign_in
{
    public partial class MainForm : Form
    {
        private string f_no;
        private string f_name;

        public string f_No
        {
            get
            {
                return this.f_no;
            }
            set
            {
                this.f_no = value;
            }
        }

        public string f_Name
        {
            get
            {
                return this.f_name;
            }
            set
            {
                this.f_name = value;
            }
        }

        public MainForm()
        {
            InitializeComponent();            
        }

       private void button1_Click(object sender, EventArgs e)
        {
            Child child = new Child();
            if (child.ShowDialog() == DialogResult.OK)
            {
                this.textBox1.Text = child.c_No;
                this.textBox2.Text = child.c_Name;
            }
        }
    }
}