Thursday, February 23

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

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.
Download source from codeProject - 3.83 KB 
Thanks Shibashish Mohanty

1 comment:

Please don't spam, spam comments is not allowed here.

ShibashishMnty
shibashish mohanty