看範例學C#-11 共用Click事件

  • 21097
  • 0
  • C#
  • 2011-10-08

看範例學C#-11 共用事件

共用一個Click事件的好處,程式碼變短了,也容易閱讀,
此例的功能是共用同一個Click事件,當按下button時,顯示該button的Text文字


如果一個按鈕一個事件的話,程式碼就是像下面那麼長,本例使用三個按鈕,有15行

        private void button1_Click(object sender, EventArgs e)
        {
            Button btn = (Button)sender;
            MessageBox.Show(btn.Text);
        }
        private void button2_Click(object sender, EventArgs e)
        {
            Button btn = (Button)sender;
            MessageBox.Show(btn.Text);
        }
        private void button3_Click(object sender, EventArgs e)
        {
            Button btn = (Button)sender;
            MessageBox.Show(btn.Text);
        }

如果我們共用同一個click事件,程式碼只有5行


        private void button1_Click(object sender, EventArgs e)
        {
            Button btn = (Button)sender;
            MessageBox.Show(btn.Text);
        }
為了方便使用,我在InitializeComponent(); 下加上以下程式碼
            button1.Click += new System.EventHandler(button1_Click);//按下button1觸發button1_Click
            button2.Click += new System.EventHandler(button1_Click);//按下button2觸發button1_Click
            button3.Click += new System.EventHandler(button1_Click);//按下button3觸發button1_Click

 

以下為此範例之完整原始碼

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 ex11
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
            button1.Click += new System.EventHandler(button1_Click);//按下button1觸發button1_Click
            button2.Click += new System.EventHandler(button1_Click);//按下button2觸發button1_Click
            button3.Click += new System.EventHandler(button1_Click);//按下button3觸發button1_Click
        }

        private void button1_Click(object sender, EventArgs e)
        {
            Button btn = (Button)sender;
            MessageBox.Show(btn.Text);
        }
        //private void button2_Click(object sender, EventArgs e)
        //{
        //    Button btn = (Button)sender;
        //    MessageBox.Show(btn.Text);
        //}
        //private void button3_Click(object sender, EventArgs e)
        //{
        //    Button btn = (Button)sender;
        //    MessageBox.Show(btn.Text);
        //}
    }
}

ex11.rar


如有錯誤 歡迎指正