event handlers

  • Thread starter Thread starter frazer
  • Start date Start date
F

frazer

hi i am looking at a colleagues code and i fail to understand what these
mean.

public event DataListItemEventHandler ItemSelect
{
add
{
this.Events.AddHandler(EventItemSelect, value);
}
remove
{
this.Events.RemoveHandler(EventItemSelect, value);
}
}

/// <summary>
/// Fired when data list item is selected
/// </summary>
public event DataListItemEventHandler ItemSelected
{
add
{
this.Events.AddHandler(EventItemSelected, value);
}
remove
{
this.Events.RemoveHandler(EventItemSelected, value);
}
}

i am aware of events but what is this add and remove any small example about
these would be great
 
Hi, I think your friend is trying a "Source and Receiver" thingy. The code looks a bit dodgy though

Basically he/she is binding the source to the receiver, if you want to try it for yourself, try

1. Create the source class and delegate

// delegate the RECEIVER has to implemen
public delegate void AnEventHandler(string msg)

// the source clas
public class Sourc

// event handle
public event AnEventHandler OnAnEventHandler

// method to raise the even
public void RaiseEvent(string msg

OnAnEventHandler(msg); // Fir



2. Create the receiver to listen and act on the event

// the receiver clas
public class Receive

// The receiver has to know about the event sourc
Source theSource

public Receiver(Source src

// bind the sourc
theSource = src


// event handle
private void EventMessage(string msg

Console.WriteLine("Message is {0}", msg)


// subscribe to the even
public void AddEvent(

theSource.OnAnEventHandler += new AnEventHandler(EventMessage)


// unsubscribe from the even
public void RemoveEvent(

theSource.OnAnEventHandler -= new AnEventHandler(EventMessage)



3. Next, test it

static void Main(string[] args

// create a sourc
Source src = new Source()

// create a receiver and bind it to the sourc
Receiver rcv = new Receiver(src)

// subscribe to even
// receiver is ready and listening for event
rcv.AddEvent()

// raise even
src.RaiseEvent("Hello all!!!")

// unsubscribe from even
rcv.RemoveEvent()
}
 
Back
Top