Basic Event Handling in .NET

November 26, 2007 at 9:35 am (.NET, ASP.NET)

Event:

Almost all users using the GUI operating system must be knowing what is event?. Event takes place when an user interacts with the GUI(Event is not always initiated by user). The event inturn invokes methods(Event handler) to handle the event.

Various common events are:
Click
TextChanged
MouseHover
MouseMove
MouseEnter
gotFocus
lostFocus
KeyPress
KeyUp
KeyDown etc.

In addition the User can create his own events.

The simple example for the Event handling is explained here:-

  • Create a windows or web application.
  • Add a Button and double click it.
  • The following code will be generated in the code behind file,

Code:
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
End Sub

This is a method name Button1_Click which has two parameters namely sender and an instance of EventArgs. This method handles the click event of the Button1.

We can also use this method to handle other events by adding the [Controlname].[Eventname] to the handle part.For Example, We add another button named Button2 and change the code as follows

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click,Button2.Click
End Sub

It means that the click event for both Controls namely Button1 and Button2 will handled by the sub-procedure Button1_Click

<font color=”red” >Note:</font>

Also note that we can change the method name as needed. For example we can change the above code as follows,

Private Sub ClickHandling(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click,Button2.Click
End Sub

We have changed the method name as ClickHandling.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: