您的位置:首页 > 其它

委托传值

2016-06-28 16:38 169 查看
点击Form1的按钮,把文本框的值传给Form2。再点击Form2的按钮,把文本框的值传给Form1。

Form1代码:

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

namespace 委托传值
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}

private void btn1_Click(object sender, EventArgs e)
{
Form2 frm2 = new Form2(txt1.Text,doSth);//Form2构造方法
frm2.Show();
}
//把窗体2的字符串给窗体1
public void doSth(string msg)
{
txt1.Text = msg;
}
}
}


Form2的代码:

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

namespace 委托传值
{
public delegate void MyDel(string str);//定义委托
public partial class Form2 : Form
{
public Form2()
{
InitializeComponent();//初始化窗体
}
private MyDel _del;//实例化委托
public Form2(string str,MyDel del)
{
InitializeComponent();//初始化窗体
txt2.Text = str;
this._del = del;//构造方法传参
}
private void Form2_Load(object sender, EventArgs e)
{

}

private void btn2_Click(object sender, EventArgs e)
{
//调用委托前先判定
if (this._del != null)
{
this._del(txt2.Text);//调用委托

}
this.Close();
}

}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: