C#子視窗與父視窗互動(使用委託和事件)

來源:互聯網
上載者:User

標籤:

目標:在子視窗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#子視窗與父視窗互動(使用委託和事件)

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.