方法1:和VB中一样,定义全局变量。
首先,先建一个类,再定义一个共有的静态的变量。
public class Class1
{
public static int i;
}
再建立两个窗体,Form1和Form2。
Form1中:
private void button1_Click(object sender, EventArgs e)
{
Form2 f = new Form2();
f.Show();
}
private void textBox1_TextChanged(object sender, EventArgs e)
{
Class1.i = Convert.ToInt32( textBox1.Text);
}
Form2中:
private void Form2_Load(object sender, EventArgs e)
{
label1.Text = Class1.i.ToString();
}
效果如图:
这个和VB差不多,我也就不多介绍了。
方法二:委托
具体我就不讲了,请大家看刘子腾的这篇博客。
http://blog.csdn.net/liuziteng0228/article/details/69829969
我来演示代码吧。
Form1:
private void button1_Click(object sender, EventArgs e)
{
Form2 f = new Form2(ShowText);
f.Show();
}
//Form2传送过来的数据 赋值给label1
void ShowText(string str)
{
label1.Text = str;
}
Form2:
namespace WindowsFormsApplication1
{
public delegate void DelTest(string str);//声明委托
public partial class Form2 : Form
{
private DelTest _del;
public Form2(DelTest del)
{
this._del = del;
InitializeComponent();
}
private void textBox1_TextChanged(object sender, EventArgs e)
{
this._del(textBox1.Text);
}
效果:
运用委托,在窗体实例化的时候就根据不同的参数实例化出不同的窗体,而第一种方法还需要点击按钮来触发事件才能再次实例化这个窗体。