学习C#已经两个多月了,当初觉得C#仅仅是拖拖控件而已,直到碰到公司里的一个牛人,才真正觉得C#是一门优秀的语言,应该静下心来好好去学。在实践的过程中碰到了需要窗体间传值的问题,网上搜了下发现有不少的方法。个人试了两种方法感觉可以,一种是将一个窗体实例作为参数传给另一个窗体,另一种是利用委托、事件的方式。
假如有两个窗体,一个主窗体一个子窗体,在你的当前窗体是子窗体这种情况下想去调用主窗体(及其控件)的时候,如果直接实例化主窗体是不行的,你new出来的这个主窗体实例已不是原来的那个主窗体对象了。
假定主窗体(FrmMain)和子窗体(FrmChild)中都有一个文本框控件和一个按钮控件,在主窗体的文本框中输入内容后点击按钮,显示子窗体同时子窗体中的文本框显示主窗体文本框的内容。修改子窗体文本框中的内容后点击按钮,关闭子窗体同时更新主窗体文本框中的内容。
方法一:将主窗体实例作为参数传给子窗体
主窗体:
public partial class FrmMain : Form
{
public string txtMainValue //定义公有属性
{
get { return txtMain.Text; }
set { txtMain.Text = value; }
}
public FrmMain()
{
InitializeComponent();
}
private void btnMain_Click(object sender, EventArgs e)
{
FrmChild fchild=new FrmChild(this);
fchild.txtChildValue=txtMainValue;
fchild.Show();
}
}
子窗体:
public partial class FrmChild : Form
{
public string txtChildValue //定义公有属性
{
get { return txtChild.Text; }
set { txtChild.Text = value; }
}
private FrmMain frmmain = null; //定义一个主窗体变量用来保存主窗体实例
public FrmChild(FrmMain fmain)
{
InitializeComponent();
frmmain = fmain;
}
private void btnChild_Click(object sender, EventArgs e)
{
frmmain.txtMainValue = txtChildValue;
this.Close();
}
}
方法二:利用委托事件
主窗体:
public partial class FrmMain : Form
{
public FrmMain()
{
InitializeComponent();
}
private void btnMain_Click(object sender, EventArgs e)
{
FrmChild fchild = new FrmChild();
fchild.txtChildValue = txtMain.Text;
fchild.DeliverEvent += new DeliverDelegate(
(strtext) =>
{ txtMain.Text = strtext; }
);
fchild.Show();
}
}
子窗体:
public delegate void DeliverDelegate(string str); //定义委托
public partial class FrmChild : Form
{
public event DeliverDelegate DeliverEvent; //定义事件
public string txtChildValue
{
get { return txtChild.Text; }
set { txtChild.Text = value; }
}
public FrmChild()
{
InitializeComponent();
}
private void btnChild_Click(object sender, EventArgs e)
{
DeliverEvent(txtChildValue); //触发事件
this.Close();
}
}