Jacklovely

导航

 

说明(2017-11-23 19:31:53):

1. 关于委托和窗体传值,一下午在网上查阅了大量资料,基本就是CSDN的论坛和博客园的文章,大家都在举例子,烧水、鸿门宴,看评论说还看到过沙漠足球的,真是跪了。。

2. 最后还是看一直了CZ杨洪波三层里的窗体传值,照着把代码写出来的,其实我第一次听说“窗体传值”这个概念,就是听得杨洪波讲的这个。

3. 最关键的一步,就是把字符串和方法,作为Form2的参数,传给Form2。

4. 虽然前面做了好几个委托的例子,也知道委托怎么写,但是这个传值就是不知道怎么写,一开始一直以为要把委托写在Form1里,谁知道是写在Form2里的!

5. 蒋坤是让写一个点击改变Form1的背景颜色,应该比窗体传值简单,或者说是一个套路,我试一下。

Form1:

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 _07_窗体传值
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            Form2 f2 = new Form2(tb1.Text, DoSth);
            f2.Show();
        }
        //这个方法通过Form2的构造函数传过去
        public void DoSth(string str)
        {
            tb1.Text = str;
        }

    }
}

Form2:

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 _07_窗体传值
{
    //委托要定义在Form2里面
    public delegate void MyDel(string str);
    public partial class Form2 : Form
    {
        public Form2()
        {
            InitializeComponent();

        }
        //声明一个委托变量,接收Form2传过来的委托
        private MyDel _mdl;
        //精髓就在于Form2的构造函数,把Form1的值和DoSth方法传到Form2里面,this是为了继承Form2窗体,省去了InitializeComponent()这一行
        public Form2(string str, MyDel mydel)
            : this()
        {
            tb2.Text = str;
            this._mdl = mydel;
        }

        private void button1_Click(object sender, EventArgs e)
        {
            //调用委托之前一定要判断委托是否为空
            if (_mdl != null)
            {
                _mdl(tb2.Text);
                this.Close();
            }
        }

    }
}

效果是这样婶儿的:

首先:

其次:

 

posted on 2017-11-23 19:38  Jacklovely  阅读(362)  评论(0编辑  收藏  举报