• windows form (窗体) 之间传值小结


    windows form之间传值,我总结了有四个方法:全局变量、属性、窗体构造函数和delegate

    第一个全局变量:

    这个最简单,只要把变量描述成static就可以了,在form2中直接引用form1的变量,代码如下:

    form1中定义一个static变量public static int i= 9 ;

    Form2中的钮扣按钮如下:

    private void button1_Click(object sender, System.EventArgs e)

    {

        textBox1.Text = Form1.i.ToString();

    }

     

    第二个方法是利用属性,请详见我的博客:

    http://blog.csdn.net/tjvictor/archive/2006/06/04/772711.aspx

     

    第三个方法是用构造函数:

    Form1 的button按钮这样写:

    private void button1_Click(object sender, System.EventArgs e)

    {

        Form2 temp = new Form2( 9 );

        temp.Show();

    }

     

    Form2 的构造函数这样写:

    public Form2( int i )

    {

        InitializeComponent();

        textBox1.Text = i.ToString();

    }

     

    第四个方法是用delegate,代码如下:

    Form2中先定义一个delegate

    public delegate void returnvalue( int i );

    public returnvalue ReturnValue;

    form2 中的button按钮代码如下:

    private void button1_Click(object sender, System.EventArgs e)

    {

        if ( ReturnValue != null )

            ReturnValue( 8 );

    }

     

    Form1中的button按键如下:

    private void button1_Click(object sender, System.EventArgs e)

    {

        Form2 temp = new Form2( );

        temp.ReturnValue = new temp.Form2.returnvalue( showvalue );

        temp.Show();

    }

     

    private void showvalue( int i )

    {

        textBox1.Text = i.ToString();

    }

     

    点击form2的button,form1中的textbox中的值就会相应变化。

     

    在这四个方法中,

    第一个是双向传值,也就是说,form1和form2改变i的值,另一方也会受到影响。

    第二个方法可以单向也可以双向传值。

    第三个方法是form1->form2单向传值。

    第四个方法是form2->form1单向传值。

     

    以后有新的方法我再补充,还有一个就是用event,和delegate差不多,在这里就不说了。

     

    转自:http://blog.csdn.net/tjvictor/article/details/824617

  • 相关阅读:
    MIne FirstBlog
    P6563 [SBCOI2020]一直在你身旁
    P6563 [SBCOI2020]一直在你身旁
    T122085 [SBCOI2020]时光的流逝
    LC 918. Maximum Sum Circular Subarray
    1026 Table Tennis
    LC 1442. Count Triplets That Can Form Two Arrays of Equal XOR
    LC 1316. Distinct Echo Substrings
    LC 493. Reverse Pairs
    1029 Median (二分)
  • 原文地址:https://www.cnblogs.com/xiurui12345/p/2442801.html
Copyright © 2020-2023  润新知