C#基础练习(使用委托窗体传值)

主界面:


Form1中的代码:

namespace _06委托练习_窗体传值
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }


        private void btn1_Click(object sender, EventArgs e)
        {
            Form2 f2=new Form2(txt1.Text,DoSth);//传过去一个字符串和DoSth方法
            f2.Show();
        }


        //把字符串变量的值赋值给文本框
        public void DoSth(string str)
        {
            this.txt1.Text = str;
        }
    }
}


Form2中的代码:

namespace _06委托练习_窗体传值
{
    public delegate void MyDel(string str);//定义一个委托
    public partial class Form2 : Form
    {
        
        public Form2()
        {
            InitializeComponent();
        }


        private MyDel _mdl;//实例化一个委托变量
        public Form2(string str,MyDel mdl):this()
        {
            this.txt2.Text = str;
            this._mdl = mdl;
        }


        private void btn2_Click(object sender, EventArgs e)
        {
            if (this._mdl!=null)
            {
                this._mdl(txt2.Text);
                this.Close();
            }
        }
    }
}

 

posted @ 2016-01-15 21:50  虚-染D  阅读(301)  评论(0编辑  收藏  举报