winform下窗口之间委托传值
大致思路:form1中定义一个委托,然后创建form2对象,通过form2的构造函数传过去一个方法作为参数,而在form2中声明一个委托类型的变量作为参数的构造函数...
//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 窗口值1
{
public delegate void ChangFormValue(string s1);//定义一个带参数的委托,接收form2的textbox1.text值
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
Form2 f2 = new Form2(Chang);
f2.ShowDialog();
}
public void Chang(string s2)
{
textBox1.Text = s2;
}
}
}
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 窗口值1
{
public partial class Form2 : Form
{
private ChangFormValue cv;
public Form2()
{
InitializeComponent();
}
public Form2(ChangFormValue cvalue)
:this()//cvalue==form1传过来的Chanag方法(方法作为参数)
{
this.cv = cvalue;//委托申明的变量指向传过来的方法
}
private void textBox1_TextChanged(object sender, EventArgs e)
{
cv(textBox1.Text);//在上面cv指向chang方法后,就可以大胆的使用chang的方法了
}
private void Form2_Load(object sender, EventArgs e)
{
}
}
}