How to Fire event from UserControl to Parent aspx page ?


UserControlClick
Hi

This is one of the frequently used function of user control. For example you have created some user control and from user control you have to fire some event in parent asp.net page.

Then you have to expose event like this

Step 1: Create one simple User Control with one button control


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

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


Step 2: Write code for exposing event like this


using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class Hello : System.Web.UI.UserControl
{
    protected void Page_Load(object sender, EventArgs e)
    {

    }
    public event EventHandler BtnClick;

    protected void btnClick_Click(object sender, EventArgs e)
    {
        BtnClick(this, EventArgs.Empty);
    }
}

Step 3: Now create one aspx page and implement the usercontrol in this page like this


<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Hello.aspx.cs" Inherits="Hello" %>
<%@ Register TagPrefix="user" TagName="HelloUserControl"  Src="~/Hello.ascx" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    <user:HelloUserControl ID="usrControlTest" runat="server" OnBtnClick="usrControlTest_Click" /> <br /><br />

    <asp:Label ID="lblmsg" runat="server" />
    
    </div>
    </form>
</body> 
</html>


Step 4: write the code in code behind file like this


using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class Hello : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {

    }
    protected void usrControlTest_Click(object sender, EventArgs e)     
    {
        lblmsg.Text = "Hello User Control";
    }
}

Note : Here we are firing event from user control on button click event

I hope this will help to some one.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: