C#实现窗体中数据的实时交互

前言

在窗体应用中,经常会遇到两个窗口中数据的实时交互问题,而在C#中我们不能直接在一个窗体中更改其他窗体中控件的属性,所示难以直接实现两个窗体之间的实时交互。在这里提出一种利用委托实现两个窗体数据交互的方法。


1、新建两个windows窗体Form1和Form2

(1)Form1中添加一个按钮button1和一个文本框textBox2
(2)Form2中添加一个文本框textBox1

2、 利用委托实现Form1和Form2之间的数据交互
(1) 编辑按钮button1实现:点击按钮后弹出窗体Form2,如下所示:

private void button1_Click(object sender, EventArgs e)
{
    Form2 windows1 = new Form2(); //实例化窗体Form2
    windows1.Show();              //显示窗体2
}

(2) 创建方法实现:更改文本框textBox2的Text属性,如下所示:

public void Setlabel(string str) 
{
     textBox2.Text = str;      
}

(3) 创建静态窗体与窗体1相互关联

public static Form1 form1 = null; 
public Form1()
{
    form1 = this;
    InitializeComponent();  
}

(4) 在窗体2中利用委托引用窗体1的Setlabel方法

private void textBox1_TextChanged_1(object sender, EventArgs e)
{
    setlabel lbl = Form1.form1.Setlabel;
    lbl(textBox1.Text);
}

3、 完整代码
(1) 窗体1

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;
using static System.Net.Mime.MediaTypeNames;

namespace 委托应用_窗体数据的交互显示
{
    public partial class Form1 : Form
    {
        public static Form1 form1 = null;        
        public Form1()
        {
            form1 = this;
            InitializeComponent();  
        }
        public void Setlabel(string str) 
        {
            textBox2.Text = str;      
        }
        private void button1_Click(object sender, EventArgs e)
        {
            Form2 windows1 = new Form2();
            windows1.Show();
        }
    }
}

(2) 窗体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.Tasks;
using System.Windows.Forms;

namespace 委托应用_窗体数据的交互显示
{
    public partial class Form2 : Form
    {
        public Form2()
        {
            InitializeComponent();
        }
        delegate void setlabel(string str);

        private void textBox1_TextChanged_1(object sender, EventArgs e)
        {
            setlabel lbl = Form1.form1.Setlabel;
            lbl(textBox1.Text);
        }
    }
}
  • 22
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值