用静态变量和静态方法也可是现实在窗体间相互传值,但是有时候那些变量和方法未必能弄成静态的。
所以窗体间传递数值莫过于使用委托和事件了。
现有两个窗体form1,form2,它们都有分别有一个textbox和一个button,分别命名为:textbox1,button1和textbox21,button2。
当点击form1的button1时打开form2,form1不关闭。
然后在form2的textbox2输入一个值,
点击form2的button2时,form1的textbox1得到form2的textbox2值。
代码如下:
Form1.cs
=============================================
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();
}
//用委托和事件
//public delegate void EventHandler(stringmsg);//这句用在form2里面
private void button1_Click(object sender,EventArgs e)
{
Form2 f2 =new Form2();
f2.Show();
f2.OnClickEvent += new Form2.EventHandler(GetText);
//f2.OnClickEvent += newf2.EventHandler(GetText);//不能用f2,只能用上面那句
}
private void GetText(string msg)
{
this.textBox1.Text = msg;
}
}
}
===========================
Form2.cs
===========================
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 Form2: Form
{
public Form2()
{
InitializeComponent();
}
//在Form2中
//用委托和事件
public delegate void EventHandler(stringmsg);
public event EventHandler OnClickEvent;//此事件写在另一个窗体中
private void button2_Click(object sender,EventArgs e)
{
OnClickEvent(this.textBox2.Text);
}
}
}
=========================
基于
http://topic.csdn.net/u/20090415/23/eda88862-e08d-49df-9793-93d232d94f70.html
修改和修正的
因为他上面的,我愣是没弄出来,始终有错误提示。
转载时补充PS:
语句顺序错了,应该先设置委托,在show窗口。
转载时补充PS:
语句顺序错了,应该先设置委托,在show窗口。
private void button1_Click(object sender,EventArgs e)
{
Form2 f2 =new Form2();
//f2.Show(); 原先的位置
f2.OnClickEvent += new Form2.EventHandler(GetText);
//f2.OnClickEvent += newf2.EventHandler(GetText);//不能用f2,只能用上面那句
f2.Show(); //放在这里
}