在form1.cs中
1.委托的定义
//定义一个委托 public delegate void AddUsrEventHandler(object sender, AddUsrEventHandlerArgs e);
2.事件的定义
//委托实例 public event AddUsrEventHandler UserAdded;
3.事件的引发
//按下btn之后触发事件 this.UserAdded(this,new AddUsrEventHandlerArgs(user));
在form2.cs中
1.登记事件
//登记一个事件 frm.UserAdded += new AddUsr.AddUsrEventHandler(frm_UserAdded);//按两下TAB键会自动生成
2.事件处理
//事件处理函数(回调函数) void frm_UserAdded(object sender, AddUsr.AddUsrEventHandlerArgs e) { //throw new NotImplementedException(); User user = e.Current; ListViewItem item = new ListViewItem(new string []{user.UserName,user.PassWorld,user.Memo}); listViewUsr.Items.Add(item); }
整个demo实现代码为
form1.cs
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 FrmLogin { public partial class AddUsr : Form { //定义一个委托 public delegate void AddUsrEventHandler(object sender, AddUsrEventHandlerArgs e); //委托实例 public event AddUsrEventHandler UserAdded; public AddUsr() { InitializeComponent(); } private void buttonOK_Click(object sender, EventArgs e) { if (UserAdded != null) { User user =new User(); user.UserName = this.textBoxUsrName.Text.Trim(); user.PassWorld = this.textBoxPaswd.Text; user.Memo = this.textBoxMemo.Text.Trim(); //按下btn之后触发事件 this.UserAdded(this,new AddUsrEventHandlerArgs(user)); } } //传递参数的类型 public class AddUsrEventHandlerArgs : EventArgs { public User Current {set; get;} public AddUsrEventHandlerArgs(User user) { this.Current = user; } } } }
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.Windows.Forms; namespace FrmLogin { public partial class FrmUsrList : Form { public FrmUsrList() { InitializeComponent(); } private void btnAdd_Click(object sender, EventArgs e) { AddUsr frm = new AddUsr(); //1.登记一个事件 frm.UserAdded += new AddUsr.AddUsrEventHandler(frm_UserAdded);//按两下TAB键会自动生成 frm.ShowDialog(); } //2.事件处理函数(回调函数) void frm_UserAdded(object sender, AddUsr.AddUsrEventHandlerArgs e) { //throw new NotImplementedException(); User user = e.Current; ListViewItem item = new ListViewItem(new string []{user.UserName,user.PassWorld,user.Memo}); listViewUsr.Items.Add(item); } } }
实现效果
form1.cs form2.cs