Asp.Net: Handle Usercontrol ClickEvent in Page

by Pieter Brinkman 24. March 2009 04:01

In this article we're going to create a usercontrol with a button. Place this usercontrol on a page and handle the clickEvent on that page.

Step 1, the UserControl

Create a usercontrol with a button called  'clickMeButton'.

In the codebehind of your UserControl define a delegate.

public delegate void ButtonClickedEventHandler(object sender, EventArgs e);


Then create a public EvenHandler.

public event ButtonClickedEventHandler ButtonClickedEvent;


Now add a click event to the button and on the click event fire tje ButtonClickedEvent.

protected void clickMeButton_Click(object sender, EventArgs e)
{
   ButtonClickedEvent(sender, e);
}

And the usercontrol is finished, now create a page to use the usercontrol.


Step 2, the Page

Create a new page. Add the usercontrol to the page, in the codebehind (Page_Load) attach your page to the ButtonClickedEvent.

UcWithClickEvent1.ButtonClickedEvent += new UcWithClickEvent.ButtonClickedEventHandler(UcWithClickEvent1_ButtonClickedEvent);


Press tab twice to generate the following Method.

void UcWithClickEvent1_ButtonClickedEvent(object sender, EventArgs e)
{
   throw new NotImplementedException();
}


Lets implement some basic logic to the event to test if the event is working

void UcWithClickEvent1_ButtonClickedEvent(object sender, EventArgs e)
{
   Response.Write("Button clicked");
}


Step3, the result

Here is the result after the user clicked the button within the usercontrol. As aspect-ed the Button Clicked text is shown.


You can download the example here (blogExamples.rar (17.87 kb))

Hope it helps!

Categories: ASP.Net | Controls