C# 窗体间传值
窗体控件都是私有变量,不能直接进行传值。
本文主要介绍两种窗体间传值的方法,通过事件或委托进行传值。
通过事件传值
目标
在父类窗体和子类窗体中定义一个TextBox和按钮;
在父类窗体中点击按钮将字符串输出到子类窗体;
在子类窗体中点击按钮将字符串输出到父类类窗体;
定义一个消息类
该消息类继承EventArgs类
public class FrmEventArgs:EventArgs
{
string _myString;
public string MyString
{
get { return _myString; }
set { _myString = value; }
}
}
父类窗口代码编写
public event EventHandler TranValue;//定义事件
private void button1_Click(object sender, EventArgs e)
{
Form2 frm = new Form2();
string Value = textBox1.Text.ToString();
this.TranValue += new EventHandler(frm.ChangeValue);//绑定事件,传出值
frm.TranValue += new EventHandler(ChangeValue);//绑定事件,传回值
FrmEventArgs FrmArgs = new FrmEventArgs();//定义消息
if (textBox1.Text != null)
{
FrmArgs.MyString = textBox1.Text;
TranValue(this, FrmArgs);//事件发生
}
frm.ShowDialog();
}
//传回消息时,处理函数
public void ChangeValue(object sender, EventArgs e)
{
FrmEventArgs args = e as FrmEventArgs;
textBox1.Text = args.MyString;
}
子类代码
public event EventHandler TranValue;//定义事件
private void button1_Click(object sender, EventArgs e)
{
FrmEventArgs FrmArgs = new FrmEventArgs();//定义消息
if (textBox1.Text != null)
{
FrmArgs.MyString = textBox1.Text;
TranValue(this, FrmArgs);//消息发生
}
this.Close();
}
//事件处理函数
public void ChangeValue(object sender, EventArgs e)
{
FrmEventArgs args = e as FrmEventArgs;
textBox1.Text = args.MyString;
}
通过委托传值
实际上就是将父类窗体的函数地址给子类窗体,子类窗体要传回值时,通过地址找到父类函数。
父类代码
private void button1_Click(object sender, EventArgs e)
{
if(textBox1.Text != null)
{
Form2 frm = new Form2();
frm.ChangeValue(textBox1.Text, ChangeValue);
frm.ShowDialog();
}
}
public void ChangeValue(string str)
{
textBox1.Text = str;
}
子类代码
public delegate void MyDelegate(string str);
public MyDelegate myDelegate;
private void button1_Click(object sender, EventArgs e)
{
if (textBox1.Text != null)
{
myDelegate(textBox1.Text);
this.Close();
}
}
public void ChangeValue(string str, MyDelegate myDele)
{
textBox1.Text = str;
myDelegate = myDele;
}