窗体间的数据传递:
下面是窗体设计还有代码,有些步骤就不用多说了,呵呵
在Form2窗体中右键查看代码,添加如下代码
/// <summary>
/// 自定义事件参数类,继承自EventArgs
/// </summary>
public class NameInputCompleteEventArgs : EventArgs
{
public readonly string firstName, middleName, lastName;
/// <summary>
/// 构造函数并初始化变量
/// </summary>
/// <param name="first"></param>
/// <param name="middle"></param>
/// <param name="last"></param>
public NameInputCompleteEventArgs(string first, string middle, string last)
{
this.firstName = first;
this.middleName = middle;
this.lastName = last;
}
}
public delegate void NameInputCompleteEventHandler(object sender, NameInputCompleteEventArgs e);//声明委托
public event NameInputCompleteEventHandler NameInputComplete;//声明事件
在设计窗体中双击OK键入如下代码: private void btnOk_Click(object sender, EventArgs e) // 用户点击OK时,输入完毕
{//创建事件参数类对象
NameInputCompleteEventArgs arg = new NameInputCompleteEventArgs(textBox1.Text, textBox2.Text, textBox3.Text);
if (NameInputComplete != null)
NameInputComplete(this, arg);
this.Hide();
}
双击Cancel,写入this.Close();Form2操作完成
Form3中也是类似的:
在Form3窗体中右键查看代码,添加如下代码
public class NameInputCompleteEventArgs : EventArgs
{
public readonly string Street,City,State,ZipCode;
public NameInputCompleteEventArgs(string street, string city, string state,string zipcode)
{
this.Street = street;
this.City = city;
this.State = state;
this.ZipCode = zipcode;
}
}
public delegate void NameInputCompleteEventHandler(object sender, NameInputCompleteEventArgs e);
public event NameInputCompleteEventHandler NameInputComplete;
在设计窗体中双击OK键入如下代码
private void btnOk_Click(object sender, EventArgs e)
{
NameInputCompleteEventArgs arg = new NameInputCompleteEventArgs(textBox4.Text, textBox5.Text, textBox6.Text, textBox7.Text);
if (NameInputComplete != null)
NameInputComplete(this, arg);
this.Hide();
}
双击Cancel,写入this.Close();Form3操作完成
步骤五:
在Form1设计窗体中右键查看代码
private Form2 fm2;
private Form3 fm3;
public Form1()
{
InitializeComponent();
fm2 = new Form2();
fm3 = new Form3();
fm2.NameInputComplete += this.fm2_NameInputComplete;//Form2的NameInputComplete事件与响应程序进行关联
fm3.NameInputComplete += this.fm3_NameInputComplete; //Form3的NameInputComplete事件与响应程序进行关联
}
首先双击第一个Set按钮,显示Form2, fm2.Show();
手动输入代码Form2输入完毕的事件响应程序
private void fm2_NameInputComplete(object sender, Form2.NameInputCompleteEventArgs e)
{
textBox1.Text = e.firstName;
textBox2.Text = e.middleName;
textBox3.Text = e.lastName;
}
接着在Form1代码窗口中添加
双击第二个Set按钮,显示Form3, fm3.Show();
private void fm3_NameInputComplete(object sender, Form3.NameInputCompleteEventArgs e)//Form3输入完毕的响应程序
{
textBox4.Text = e.Street;
textBox5.Text = e.City;
textBox6.Text = e.State;
textBox7.Text = e.ZipCode;
}
最后一个退出按钮:Application.Exit();//关闭所有应用程序窗口