Creating and invoking custom events


With the help of this article you learn about Creating and invoking custom events

Events are used to handle the situations dynamically. Let say almost in all the windows application we are using button control, and the click event of it. Actually the click is happening in the button control, but user [we] able to handle the click event in form. The same way we can use the events for our own controls, business objects etc.

Example:
Class “Store” is used to add and delete the items. Also the class has the event called “OnDelete”, which is used to handle something before the delete operation. The user of the “Store” class can write his codes required to execute before the delete operation.

In this example I have handled the OnDelete event to show the warning message while deleting.



// Declare a delegate for the event handler.
public delegate void StoreEventHandler(string itemName,ref bool action);

public class Store
{
// Declare an event handler
public event StoreEventHandler OnDelete;

private Dictionary ItemList = new Dictionary();

public void Add(int Id,string Name)
{
ItemList.Add(Id,Name);
}

public void Delete(int Id)
{
bool canDelete=false;

//fire the on delete event[s]
OnDelete(ItemList[Id], ref canDelete);

if (canDelete)
{
ItemList.Remove(Id);
MessageBox.Show("Item Deleted sucessfully");
}
else
{
MessageBox.Show("Deletion canceld by the user");
}
}
}


How to use the Store object in your application:


public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}

private void Form1_Load(object sender, EventArgs e)
{
Store myStore = new Store();
myStore.OnDelete += new StoreEventHandler(myStore_OnDelete);

myStore.Add(1, "Milk");
myStore.Add(2, "Biscuts");

myStore.Delete(2);
}

void myStore_OnDelete(string itemName, ref bool action)
{
DialogResult r = MessageBox.Show("Are you sure you want to delete item '"+itemName+"' from the store","Confirm Item Delete", MessageBoxButtons.YesNo);
if (r == DialogResult.Yes)
{
action = true;
}
else
{
action = false;
}
}
}


Comments

Author: mani08 May 2008 Member Level: Silver   Points : 2

good it is nice



  • Do not include your name, "with regards" etc in the comment. Write detailed comment, relevant to the topic.
  • No HTML formatting and links to other web sites are allowed.
  • This is a strictly moderated site. Absolutely no spam allowed.
  • Name:
    Email: