Create Custom Event Class: derived from EventArgs class
{
public CustomEvent(string message)
{
this.Message = message;
}
public string Message
{
get;
set;
}
}
declare a delegate out side the Class:
public delegate void CustomEventHandler(object sender,CustomEvent args);
public class Branch
{
BranchNameCollection _branchNames;
#region --Event Raised when item is Removed--
//public event EventHandler itemRemoved;
public event CustomEventHandler itemRemoved;
public event CustomEventHandler itemAdded;
public event CustomEventHandler itemReplaced;
#endregion
public Branch()
{
this._branchNames = new BranchNameCollection(this);
}
#region Property
public Collection
{
get { return _branchNames; }
}
#endregion
//---called from within the BranchNamesCollection class when item Removed---
protected virtual void RaiseItemRemovedEvent(CustomEvent e)
{
if (itemRemoved != null)
itemRemoved(this, e);
}
//---called from within the Branchnamecollection class when item to be added----
protected virtual void RaisedAddItemEvent(CustomEvent e)
{
if (itemAdded != null)
itemAdded(this, e);
}
protected virtual void RaisedReplaceItemEvent(CustomEvent e)
{
if (itemReplaced != null)
itemReplaced(this, e);
}
public string Message
{
get; set;
}
private class BranchNameCollection : Collection
{
Branch _b;
public BranchNameCollection(Branch b)
{
this._b = b;
}
//---fired when an item is removed---
protected override void RemoveItem(int index)
{
_b.RaiseItemRemovedEvent(new CustomEvent(_b.BranchNames[index].ToString()));
base.RemoveItem(index);
}
//---fired when an item Added---
protected override void InsertItem(int index, string item)
{
base.InsertItem(index, item);
_b.RaisedAddItemEvent(new CustomEvent(_b.BranchNames[index].ToString()));
}
//---fired when an item Replaced---
protected override void SetItem(int index, string item)
{
base.SetItem(index, item);
_b.RaisedReplaceItemEvent(new CustomEvent(_b.BranchNames[index].ToString()));
}
}
}
calling the Void main()
{
//creating the object
Branch b = new Branch();
//assign Events and handle the Events
b.itemRemoved += new CustomEventHandler(b_itemRemoved);
b.itemAdded+= new CustomEventHandler(b_itemAdded);
b.itemReplaced+=new CustomEventHandler(b_itemReplaced);
b.BranchNames.Add("Mumbai");
b.BranchNames.Add("Kolkata");
b.BranchNames.Add("Bangalore");
b.BranchNames.Add("Delhi");
//Remove the item from collection
b.BranchNames.Remove("Kolkata");
}
//calling Appropriate function
static void b_itemRemoved (object sender, CustomEvent args)
{
Console.WriteLine("ItemRemoved "+ " : " + args.Message);
}
static void b_itemAdded(object sender, CustomEvent args)
{
Console.WriteLine("ItemAdded " + " : " + args.Message);
}
static void b_itemReplaced(object sender, CustomEvent args)
{
Console.WriteLine("ItemReplaced " + " : " + args.Message);
}
//
No comments:
Post a Comment