C# 委託 事件 之 表單之間互傳值

來源:互聯網
上載者:User

標籤:blog   http   os   ar   for   strong   sp   div   2014   

C# 委託 事件 之 表單之間互傳值

效果:

Form1.cs:

 

using System;using System.Windows.Forms;namespace 表單事件互傳值2{    public delegate void SetTxb2Del(string str, object obj);//定製針對Txb2的委託    public partial class Form1 : Form    {        private event SetTxb2Del st2dEvent;//聲明Txb2委託的事件        public Form1()        {            InitializeComponent();        }        private void button1_Click(object sender, EventArgs e)        {            Form2 f2 = new Form2();//執行個體化一個Form2表單            this.st2dEvent += new SetTxb2Del(f2.SetTxb2);//為事件註冊Form2中設定txb2值的方法(待執行)            this.st2dEvent(txb1.Text, this);//呼叫事件(參數傳入方法SetTxb2,並執行)            f2.ShowDialog();//展示表單        }        /// <summary>        /// 設定txb1文本的方法        /// </summary>        /// <param name="str">要設定為值的字串</param>        public void SetTxb1(string str)        {            txb1.Text = str;        }    }}

  

Form2.cs:

 

using System;using System.Windows.Forms;namespace 表單事件互傳值2{    public delegate void SetTxb1Del(string str);//定製針對Txb1的委託    public partial class Form2 : Form    {        private event SetTxb1Del st1dEvent;//聲明Txb1委託的事件        public Form2()        {            InitializeComponent();        }        private void button1_Click(object sender, EventArgs e)        {            Form1 f1 = this.Tag as Form1;//從Tag屬性得到Form1對象            this.st1dEvent += new SetTxb1Del(f1.SetTxb1);//為事件註冊Form1中設定txb1值的方法(待執行)            this.st1dEvent(txb2.Text);//呼叫事件(參數傳入方法SetTxb1,並執行)            this.Close();//關閉視窗        }        /// <summary>        /// 設定txb2文本的方法        /// </summary>        /// <param name="str">要設定為值的字串</param>        /// <param name="obj">來源物件(Form1)</param>        public void SetTxb2(string str, object obj)        {            txb2.Text = str;//設定文字框的值            this.Tag = obj;//暫存Form1對象到當前Form2的Tag屬性        }    }}

  

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.