Saturday, April 5, 2014

Event Handling

Event Handling
Def:  The  event  handling  includes  with  executing  some  code,  whenever  the  user performs an action.
The necessary code is to be written in a special method. That method is called as Event Handler.

Event Handler:

  • An  event  handler  is  a  method,  which  will  be  called  automatically,  whenever  the  user performs certain event at run time.
  • The event handler should be defined in the form class.
private void controlname_eventname(object sender, EventArgs e)
         //some code
  • In the above syntax, there are two arguments:
sender:  Represents  the  control,  based  on  which  the  event  is  raised.  For example,  in  the "button1_click"  event  handler,  the  sender  argument represents button1 control.
e: Contains some additional information about the event. For example, in the MouseClick  event,  the  position  of the  mouse  will  be represented,  where  it is clicked.
  • Event  through  you  know  the  syntax  of  event  handler  properly,  don‘t  try  to  type  it manually in the code. The event handler method should be generated through the proper way.
  • In the previous examples, you have generated the event handlers by double clicking on the controls.
  • But already you know that, for all the controls, there are multiple events. But when you double  click  the  control,  it  will  generate  the  event  handler  for  only  one  event.  That particular event can be called as Default event.
  • For example, the default event for the button is Click event.
  • If you want to implement the event handlers for other controls, you require to follow the steps given below.
Implementation of Event Handler:
  • First, in the design window, select the form or control, for which you want to create the event handler.
  • Open Properties  window,  and  click  on  Events option.
  • Select  the  required  event,  for  which  you  want  to  create the event handler.
  • Press Enter.
  • Then  the  event  handler  will  be  created  in  the  code window.

Demo on Event Handling
private void button1_Clickundefinedobject sender, EventArgs e)
  MessageBox.Showundefined"You have clicked the button");
private void button1_MouseEnterundefinedobject sender, EventArgs e)
  button1.BackColor = Color.Yellow;
  button1.ForeColor = Color.DarkRed;
 private void button1_MouseLeaveundefinedobject sender, EventArgs e)
  button1.BackColor = Color.DarkRed;
  button1.ForeColor = Color.Yellow;

No comments:

Post a Comment