委托--事件--基础以及在现在做的项目上的实际应用(二)

xiaoxiao2021-02-28  76

手头上的项目是winform的,难免进行窗体间传值和值的回传问题。传值好解决,构造函数定义需要传的参数就行,那回传呢?委托就体现价值了。

现在有Form1,Form2这两个窗体,

,当点击Form1的按钮时,把文本框中的值传给Form2,点击Form2中的按钮,把文本框的值回传给Form1。

  1、Form2构造函数接受Form1的传值,代码:

public Form2(string str) : this() { textBox1.Text = str; }

Form1按钮点击事件代码如下:

string s = textBox1.Text; Form2 f = new Form2(s); f.ShowDialog();

这样Form2就能接收到Form1传来的值了,那么Form2文本框中的值进行回传呢? 

思路:1、  Form1中的文本框From1很随意就可以获得,而且传回来的值就是要给Form1中的文本框赋值,那咱们就在Form1中定义一个给文本框赋值的方法:  

public void SetStr(string str) { textBox1.Text = str; }

  2、由于时Form2中的按钮点击回传值,使Form1的文本框改变值,那么Form2能直接调用这个方法就好了,怎么办?把这个方法给Form2,在需要的时候调用。怎么给?

用委托,上篇文章说过,委托就是把方法当作参数传递嘛。Form2改造如下:

public delegate void Mydele(string strPara); public partial class Form2 : Form { public Form2() { InitializeComponent(); } public Mydele mdele; public Form2(string str, Mydele md) : this() { textBox1.Text = str; mdele = md; } }

 3、Form1实例化Form2,进行传值的方法也需要改造为:

private void button1_Click(object sender, EventArgs e) { string s = textBox1.Text; Form2 f = new Form2(s,SetStr); f.ShowDialog(); }

4 、这样,Form2的按钮点击事件,就可以这样写了:

private void button1_Click(object sender, EventArgs e) { if (mdele!=null) { mdele(textBox1.Text); } }

5、运行,完成。 可以走调试运行,这样一步一步的加深印象。
转载请注明原文地址: https://www.6miu.com/read-75156.html

最新回复(0)