Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

Capture Button’s Click Event of User Control in the Page

0.00/5 (No votes)
4 Mar 2009 4  
Solution to capture button’s click placed in user control inside the page that holds the user control.

Introduction

Almost every application nowadays makes use of UserControl. This article helps you to understand how one can capture the button's (placed in User Control) click event inside the page which holds the user control.

Using the Code

To start with, let's first create a new website and add a user control to it and name it Demo.ascx. This is how your user control looks like initially.

<% @ Control Language="C#" AutoEventWireup="true" 
	CodeFile="Demo.ascx.cs" Inherits="Demo" %> 

Now add a button to this user control.

<% @ Control Language="C#" AutoEventWireup="true" 
		CodeFile="Demo.ascx.cs" Inherits="Demo" %>

<asp:Button ID="btnClick" runat="server" Text="Click Me!!!" onclick="btnClick_Click" />

If you want to extend the button click placed in the user control to the page, then declare an Event handler and on the click of the button just make a call to the declared event handler. This will work as a property for any web page.

public event EventHandler ButtonClickDemo;

protected void Page_Load(object sender, EventArgs e)
{
}
protected void btnClick_Click(object sender, EventArgs e)
{
   ButtonClickDemo(sender, e);
}

Place the control in your *.aspx page. In the Page_Load event of your page, assign a new event handler to the User control’s event handler property. And, now use the newly declared event handler.

public partial class _Default : System.Web.UI.Page 
{
    protected void Page_Load(object sender, EventArgs e)
    {
        Demo1.ButtonClickDemo += new EventHandler(Demo1_ButtonClickDemo);
    }

    protected void Demo1_ButtonClickDemo(object sender, EventArgs e)
    {
         Response.Write("It's working");
    }
}

Now when the button (which is placed in user control) is clicked, event handler declared in the page will be used to handle the click event.

Also, Read my series of articles on ASP.NET 5

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here