ASP.NET Event Handler

Asp.Net bases on Events. These are actions that occur on objects such a mouse click on a button. Below is an example of some of the events available:

OnClick                                      Execute when a button is clicked
OnSelectedIndexChanged              Executes when an option in dropdownlist is selected
OnCheckChanged                         Executes when a checkbox or radiobutton are checked

When an event is triggered it requests a piece of program to be executed. If you want an email to be sent you must click on the send button, this is linked to a program that will send the email over the internet. These programs are called Event Handlers, they execute at an event’s request. Below is an example of pre-defined Event Handlers:

Page_Load                                     Executes when the page load
Page_Unload                                  Executes when the page is close

Subroutine: Sub program that can take data called parameters (optional) and execute a task. It does not return a value. Subroutines are used to define event handlers.

Sub AnyNameHere(info As String)

End Sub

An event handler must be declared as follow:

Sub BTN_Click(sender as Object, e as EventArgs)

End Sub

Note that the event handler passes two arguments; sender as Object represents the object raising the event. And e as EventArgs represents the data specific to the event which is being sent to the server (if any). This is called Event Argument.

To relate an Event to an Event Handler use the following syntax on the object that will raise the event: 

<asp:button id=”btn” runat=”server” text=”Enter” OnClick=”BTN_Click()”/>

<script runat="server">
           
            sub Display(sender as object, e as EventArgs)
                        lbl.text = "some one has clicked on the button to show this message on a label"
            End sub
           
            sub Hide(sender as object, e as EventArgs)
                        lbl.text = " "
            End sub
           
</script>

<form runat="server">
            <asp:Label runat="server" ID="lbl"></asp:Label>
            <asp:Button runat="server" ID="BtnDisplay" Text="Show message" OnClick="Display"></asp:Button>
            <asp:Button runat="server" ID="BtnHide" Text="Hide Message" OnClick="Hide"></asp:Button>
</form>