Crunch Mode Blog - A State of Mind by Developers at D2Soft Technologies

Like us on Facebook

ASP.NET 2.0 Web User Control: Generate Custom Event

Here's one cool little tip you might need, if you're coding in ASP.Net using the .Net Framework 2.0.  Here's what you need:

- a Web User Control that contains a button;
- you want to trap the button click's event from your page.

Code for the Web User Control

Let's suppose your button has the ID "DeleteButton".  First, you need to create a Delegate and an Event, like this:

public delegate void OnDeleteButtonClick();
public event OnDeleteButtonClick DeleteButtonHandler;

Now, add the following method to the OnClick event of the button:

protected void DeleteButton_Click(object sender, EventArgs e)
  // Check if event is null.
  if (DeleteButtonHandler != null)

Code for your Page

Include your Web User Control into your page, let's suppose the ID "MyControl".  First, simply create an handler to receive the event in your Page_Load method:

protected void Page_Load(object sender, EventArgs e)
  // Create the handler to access callback from DeleteButton.
  MyControl.DeleteButtonHandler += new MyControl.OnDeleteButtonClick(MyControl_DeleteButtonHandler);

And define the target method to run when click occurs:

void MyControl_DeleteButtonHandler()
  // do stuff here!

That's it.  You can now enjoy events coming from your own controls.