前言

在窗体应用中,经常会遇到两个窗口中数据的实时交互问题,而在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);

}

}

}

参考阅读

评论可见,请评论后查看内容,谢谢!!!
 您阅读本篇文章共花了: