iT邦幫忙

1

[ASP.NET] C# 自訂控制項 -事件 -以asp button為例

自訂控制項event(使用已知delegate)

1.新增ascx WebForms使用者控制項
https://ithelp.ithome.com.tw/upload/images/20180801/20106764cPu8hX25n9.png
2.拉asp button
3.自訂ascx事件
3.1.建立event

public event EventHandler ButtonClickEvent;

3.2.對button點二下,於event中輸入

        protected void Button1_Click(object sender, EventArgs e)
        {
            if (ButtonClickEvent != null)    // 這一行一定要加,不然如果是null就會出錯.
                ButtonClickEvent(this, e);//用this是指這個ascx,如果用sender就是指button,如果多control可能會搞混,所以要用this
        }

使用

1.新增aspx頁面,把"自訂控制項"拉到該頁面,名稱為:WebUserControl_自訂事件1
2.新增自訂控制項中button_click事件

        protected void Page_Load(object sender, EventArgs e)
        {
            this.WebUserControl_自訂事件1.ButtonClickEvent += new EventHandler(Button3_Click);
        }

        protected void Button3_Click(object sender, EventArgs e)
        {
            Response.Write("<script>alert('hi');</script>");
        }

3.run & click buttion 查看結果
https://ithelp.ithome.com.tw/upload/images/20180801/20106764PMzWi7Fl19.png

way2 自訂事件(自訂delegate)

        public delegate void ValueChangedEvent( );
        public event ValueChangedEvent ValueChanged;
        protected void Calendar1_SelectionChanged(object sender, EventArgs e)
        {
            TextBox1.Text = Calendar1.SelectedDate.ToString("yyyy/MM/dd") ;
             if (ValueChanged != null)     
                ValueChanged( );
        }

使用

    this.WebdatechooserStartDate.ValueChanged   += new UserControl.DatePicker.ValueChangedEvent(this.WebdatechooserStartDate_ValueChanged);
    this.WebdatechooserEndDate.ValueChanged += new UserControl.DatePicker.ValueChangedEvent(this.WebdatechooserEndDate_ValueChanged);
		private void WebdatechooserStartDate_ValueChanged( )
		{
			//.........	
		}

ref
https://dotblogs.com.tw/johnny/2010/01/19/13110
http://welkingunther.pixnet.net/blog/post/30893506-%28c%23%29%E8%87%AA%E8%A8%82%E6%8E%A7%E5%88%B6%E9%A0%85%28usercontrol%29%E7%9A%84%E4%BA%8B%E4%BB%B6


尚未有邦友留言

立即登入留言