winForm 传值
时间:2011-06-02 来源:肖建
1.通过构造函数传值
2.通过静态变量传值
3.通过公共属性传值
4.公共属性结合Owner属性
窗体Form1中
public int FormValue = 1;
Form2 f2 = new Form2();
f2.ShowDialog(this);
窗体Form2中
Form1 f1 = (Form1) this.Owner;
MessageBox.Show(f1.FormValue.ToString());
//给Form1的FormValue赋值
f1.FormValue = 222;
5.通过窗体的公有属性和Application.OpenForms属性
说明:Application.OpenForms 属性:获取属于应用程序的打开窗体的集合。(此属性在.NET Framework2.0版本中)
实现代码:
窗体Form1中
pubic int FormValue = 1;
Form2 f2 = new Form2();
f2.Show();
窗体Form2中
String formName = "Form1";
Form fr = Application.OpenForm2[formName ];
if(fr != null)
{
Form1 f1 = (Form1)fr;
MessageBox.Show(f1.FormValue.Tostring());
//给Form1的FormValue赋值
f1.FormValue = 222;
6.通过事件
实现代码:
在窗体Form2中定义公有属性Form2Value,获取和设置textBox1的文本值
并且还定义一个accept事件
public string Form2Vaule
{
get {return this.textBox1.Text;}
set {this.textBox1.Text = value;}
}
public event EventHandler accpet;
private void button1_Click(object sender, EventArgs e)
{
if(accept != null)
{
accept(this,EventArgs.Empty); //当窗体事件发生时,传递自身引用
}
}
在窗体 Form1中
Form2 f2 = new Form2();
f2.accpet += new EventHandler(f2_accpet);
f2.Show();
private void f2_accpet(object sender, EventArgs e)
{
//事件的接收者通过一个简单的类型转换得到Form2的引用
Form2 f2 = (Form2)sender;
//接收到Form2 的 textBox1.Text;
this.textBox1.Text = f2.Form2Value;
}