天天看點

伺服器控件的學習-處理回發事件

要使控件捕獲回發事件,控件必須實作 System.Web.UI.IPostBackEventHandler 接口。此接口的協定允許控件在伺服器上引發事件來響應來自用戶端的回發。

public InterFace IPostbackEventhandler

    sub RaisePostBackEvent(eventArgument as string)

end interface

回發後,頁架構就會搜尋發送的内容并确定發送的名稱是否與實作IPostbackEventHandler的伺服器控件的UniqueID對應,如果對應,頁架構就會在該控件上調用RaisePostBackEvent方法

Public Overridable Sub RaisePostDataChangedEvent() Implements IPostBackDataHandler.RaisePostDataChangedEvent

   OnTextChanged(EventArgs.Empty)

End Sub

 呈現邏輯必須為控件的名稱特性配置設定 UniqueID,如下面的示例所示。如果用戶端的控件名稱特性與其 UniqueID 不比對,則頁架構無法将回發事件傳送給該控件。

Protected Overrides Sub Render(output As HtmlTextWriter)

   output.Write("<INPUT type=submit name=" & Me.UniqueID &     " Value='Click Me' />")

End Sub

全部代碼:

Option Explicit

Option Strict

Imports System

Imports System.Web.UI

Namespace CustomControls

   Public Class MyButton

      Inherits Control

      Implements IPostBackEventHandler

      ' Defines the Click event.

      Public Event Click As EventHandler

      ' Invokes delegates registered with the Click event.

      Protected Overridable Sub OnClick(e As EventArgs)

         RaiseEvent Click(Me, e)

      End Sub

      ' Method of IPostBackEventHandler that raises change events.

      Public Sub RaisePostBackEvent(eventArgument As String) Implements IPostBackEventHandler.RaisePostBackEvent

         OnClick(EventArgs.Empty)

      End Sub

      Protected Overrides Sub Render(output As HtmlTextWriter)

         output.Write("<INPUT TYPE=submit name=" & Me.UniqueID & _

               " Value='Click Me' />")

      End Sub

   End Class

End Namespace