C#窗体间传值简单小例子

来源:互联网 发布:autocad2008软件下载 编辑:程序博客网 时间:2024/06/01 23:06
本篇博客是利用C#委托与事件进行窗体间传值的简单小例子

委托与事件的详细解释大家可以参照张子阳的博客: http://www.tracefact.net/CSharp-Programming/Delegates-and-Events-in-CSharp.aspx

个人认为上面那篇文章写的还是很浅显易懂的,时间够的话建议大家仔细看看。

下面是小例子的效果Gif :

很简单的演示。只需要在form1中准备一个label一个button,在form2中准备一个textbox一个button即可。

效果就是点击form1的按钮然后出来form2,在form2的textbox中输入后点击按钮,form1中label的值改变。

代码:

Form1.cs :

using System;using System.Collections;using System.Collections.Generic;using System.ComponentModel;using System.Data;using System.Drawing;using System.Linq;using System.Text;using System.Threading.Tasks;using System.Windows.Forms;namespace WinForm1{    public partial class Form1 : Form     {        public Form1()        {            InitializeComponent();            }        private void Form1_Load(object sender, EventArgs e)        {        }        private void changeText(string s) //改变label值的方法        {            label1.Text = s;        }        private void button1_Click(object sender, EventArgs e)        {            Form2 form2 = new Form2();            form2.TextEvent += changeText; //让事件注册方法                       form2.ShowDialog();                    }    }}

Form2.cs :

using System;using System.Collections.Generic;using System.ComponentModel;using System.Data;using System.Drawing;using System.Linq;using System.Text;using System.Threading.Tasks;using System.Windows.Forms;namespace WinForm1{    public partial class Form2 : Form    {        public delegate void TextHandler(string s); //定义委托        public event TextHandler TextEvent;  //定义事件        public Form2()        {            InitializeComponent();        }        private void button1_Click(object sender, EventArgs e)        {               TextEvent(textBox1.Text); //执行事件(执行所有注册过的方法)            this.Close();            }    }}

嗯代码挺少的。依我个人理解简要概括起来就是几句话:

1、在你需要传出值的类中定义委托与事件。(如这个例子form2要向form1传值,就在form2中定义委托和事件)

2、事件注册的方法的参数要与委托的参数一致。(如这个例子form2中的委托TextHandler后面的参数是string,则form1中给事件添加的方法changeText后面的参数也应该是string)

3、想不出来了,,大家可以补充

 

其实窗体间传值还有许多种方法,比如将整个form1作为一个参数传给form2的构造函数,然后form2进行操作的时候form1也对应进行变化。但是这样做的不好之处在于,如果要添加个什么form3也和form2有关系,form2的构造函数又得改,如果多几个类进行联系那么代码就很不容易修改了。

利用委托与事件的好处就是,使类与类之间的耦合度变低,更易于扩展和封装。

最后希望大家在C#的世界中blingbling...

原创粉丝点击