C#中如何跨窗体传值

方法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);
        }

效果:

运用委托,在窗体实例化的时候就根据不同的参数实例化出不同的窗体,而第一种方法还需要点击按钮来触发事件才能再次实例化这个窗体。

评论 29
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值