0

I am learning event handling in C# and have just learnt the basic usage of

    delegates

I was looking for a way to add some events to my GUI App. for ex, check the following code:-

    private void label1_Click(object sender, EventArgs e)
    {
      MessageBox.Show("Hello World") ;  
    }

This function displays the MessageBox with the content HelloWorld whenever I click on the label label1. I wanted to know , how can we add various other events like hovering over the label and other such events. Also, what is the use of the parameter

    sender and e
Pratik Singhal
  • 6,283
  • 10
  • 55
  • 97

3 Answers3

3

label1.OnMouseHover += myDelegate will add your delegate to the mouseover event.

See list of events.

Jeroen Vannevel
  • 43,651
  • 22
  • 107
  • 170
0
label1.Click += new System.EventHandler(label1_Click);
Frank Rem
  • 3,632
  • 2
  • 25
  • 37
0

You'll get it better if you create a class and add your own event to it.

The default "e" is a an instance of System.EventArgs You can derived from that to have your own e.g.

public class MyEventArgs : System.EventArgs
{
   public string EventData {get; private set;}
   public MyEventArgs(String argEventData)
   {
       EventData = argEventData;
   }
}

Then to use the above in a class

public class SomeFellaWithAnEvent
{
   public event EventHandler<MyEventArgs> OnMyEvent;
   private int _value;
   public int Value 
   { 
     get {return _value;} 
     set 
     {
       if (_value != value) 
       {
          _value = value;
          DoEvent(_value.ToString();
       }
     }
   }


   protected void DoEvent(String argData)
   {
      if (OnMyEvent != null)
      {
          OnMyEvent(this,new MyEventArgs(argData)) 
      }
   } 
}

So now you have something where if Value get's changed it will raise an event if you've given it a handler

e.g

SomeFellaWithAnEvent o = new SomeFellaWithAnEvent()
o.OnMyEvent += someThingChanged();
o.Value = 22;

private void somethingChanged(Object sender, MyEventArgs e)
{
   // do something with it.
   // debug this and you'll see sender is the o instance above, and e is the instance
   // of MyEventArgs created in the DoEvent method and has a property set to "22"
}   

To add more event handlers to existing controls from the tool box. Click the events tab (lightning button) in the property inspector and then double click in the value.

Or in the code view type label1.Click += and then press tab twice.

Tony Hopkinson
  • 20,172
  • 3
  • 31
  • 39