winform程序两个窗体间同步数据(三):建立父窗口与子窗口的父子关系(不使用线程)

一 问题:

1 可不可以不使用线程?

 可以。需要建立父窗口和子窗口之间的父子关系。


2 如何建立父子关系?

在子窗体中增加一个类型为父窗口的属性(即ChildFrm类中设置 public ParentFrm parentFrm{get;set;}属性)。



二 显示效果


三 代码

1 入口程序

using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;

namespace WindowsFormsApplication1
{
    static class Program
    {
        /// <summary>
        /// 应用程序的主入口点。
        /// </summary>
        [STAThread]
       
        static void Main()
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
           ParentFrm parentFrm = new ParentFrm();
           Application.Run(parentFrm);//启动父窗体
        }
    }
}

2父窗体

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

namespace WindowsFormsApplication1
{
    public partial class ParentFrm : Form
    {
        public ParentFrm()
        {
            InitializeComponent();
        }
        public TextBox GetTbParent()
        {
            return this.TbParent;//TbParent 是私有的对象 ,所以要有公有的方法获取TbParent对象
        }
        private void button1_Click(object sender, EventArgs e)//点击事件
        {
            ChildFrm childFrm = new ChildFrm();
            childFrm.parentFrm = this; //建立父子关系
            childFrm.Show();//显示子窗体
        }
    }
}

3 子窗体
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 ChildFrm : Form
    {
        public ParentFrm parentFrm{get;set;}
        public ChildFrm()
        {
            InitializeComponent();
        }

        private void TbChild_TextChanged(object sender, EventArgs e)
        {

            parentFrm.GetTbParent().Text = this.TbChild.Text;//将用户输入到子窗体TEXTBOX控件中的内容放入到父窗体的TEXTBOX控件中
           
        }
    }
}




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值