有时候需要在两个窗体之间传递事件或者参数,例如一个登陆窗体,要将用户名和密码传递给主窗体,使用Event不但可以使主窗体在登录窗体关闭后再显示出来,还可以将数据传递到主窗体,代码很简单,要注意的是要判断事件是否为空,不然会出现空指向异常:
FormLogin代码:
- using System;
- using System.Collections.Generic;
- using System.ComponentModel;
- using System.Data;
- using System.Drawing;
- using System.Text;
- using System.Windows.Forms;
-
- namespace Login
- {
- public delegate void myDele(string id, string pwd);
-
- public partial class FormLogin : Form
- {
- public event myDele myEvent;
-
- public FormLogin()
- {
- InitializeComponent();
- }
-
- private void button1_Click(object sender, EventArgs e)
- {
- if (myEvent != null)
- {
- myEvent(textBox1.Text, textBox2.Text);
- }
- Close();
- }
- }
- }
Form1代码:
- using System;
- using System.Collections.Generic;
- using System.ComponentModel;
- using System.Data;
- using System.Drawing;
- using System.Text;
- using System.Windows.Forms;
-
- namespace Login
- {
- public partial class Form1 : Form
- {
- public Form1()
- {
- InitializeComponent();
- FormLogin flogin = new FormLogin();
- flogin.myEvent += new myDele(flogin_myEvent);
- flogin.ShowDialog(this);
- }
-
- void foglin_myEvent(string id, string pwd)
- {
- label1.Text = id;
- label2.Text = pwd;
- }
- }
- }
Login窗体
主窗体:
程序执行流程是:实例化主窗体时,先将Login窗体以对话框方式显示出来;在Button1按钮事件中,因为Form1中为FormLogin窗体的MyEvent添加了事件foglin_myEvent,因此在Login中执行myEvent时会调用foglin_myEvent,
并把id和pwd作为参数,这时就可以在foglin_myEvent函数中接受这些从Login窗体中来的参数了。
----------------------------------------------------------------------------------------------------------------------------------