標籤:
目標:在子視窗Form2上單擊按鈕時向Form1傳遞一組自訂參數,並顯示在父視窗Form1上。
方法:有很多方法,這裡只介紹委託和事件的實現方式。
思路:Form2中定義事件,Form1建立Form2並訂閱事件;Form2觸發事件後傳遞參數到Form1,Form1處理參數。
??
Form1代碼如下:
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 FormDataInteractive
{
/// <summary>
/// powered by shadu {at} foxmail.com
/// </summary>
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
?
private void button1_Click(object sender, EventArgs e)
{
// 建立Form2,並添加事件處理函數
Form2 frm = new Form2();
frm.DataChange += new Form2.DataChangeHandler(DataChanged);
frm.ShowDialog();
}
?
public void DataChanged(object sender, DataChangeEventArgs args)
{
// 更新表單控制項
textBox1.Text = args.name;
textBox2.Text = args.pass;
}
}
}
?
Form2代碼如下:
usingSystem;
usingSystem.Collections.Generic;
usingSystem.ComponentModel;
usingSystem.Data;
usingSystem.Drawing;
usingSystem.Linq;
usingSystem.Text;
usingSystem.Windows.Forms;
??
namespaceFormDataInteractive
{
????publicpartialclassForm2 : Form
????{
????????// 定義委託
????????// public delegate void DataChangeHandler(string x); 一次可以傳遞一個string
????????publicdelegatevoidDataChangeHandler(objectsender, DataChangeEventArgs args);
????????// 聲明事件
????????publiceventDataChangeHandler DataChange;
??
????????// 呼叫事件函數
????????publicvoidOnDataChange(objectsender, DataChangeEventArgs args)
????????{
????????????if(DataChange != null)
????????????{
????????????????DataChange(this, args);
????????????}
????????}
??
????????publicForm2()
????????{
????????????InitializeComponent();
????????}
??
????????privatevoidbutton1_Click(objectsender, EventArgs e)
????????{
????????????// 觸發事件, 傳遞自訂參數
????????????OnDataChange(this, newDataChangeEventArgs(textBox1.Text, textBox2.Text));
????????}
????}
??
????/// <summary>
????/// 自訂事件參數類型,根據需要可設定多種參數便於傳遞
????/// </summary>
????publicclassDataChangeEventArgs : EventArgs
????{
????????publicstringname { get; set; }
????????publicstringpass { get; set; }
????????publicDataChangeEventArgs(strings1, strings2)
????????{
????????????name = s1;
????????????pass = s2;
????????}
????}
}
?
?
C#子視窗與父視窗互動(使用委託和事件)