Tuesday, March 11, 2014

Asp.NET : Raise event from User Control to Default Page

Create a new project.
add item -> select "Web User Control" -> add
Write the following code in WebUserControl.ascx file :-


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

<asp:Button ID="btnTest" runat="server" Text="This is from User Control"
    OnClick="btnTest_Click" ForeColor="#FF0066" />

Then add code in the button event
WebUserControl.ascx.cs


public partial class WebUserControl : System.Web.UI.UserControl
{
    public delegate void OnButtonClick(string strValue);

    public event OnButtonClick btnHandler;
 
    protected void Page_Load(object sender, EventArgs e)
    {
     
    }

    protected void btnTest_Click(object sender, EventArgs e)
    {
           if (btnHandler != null)
               btnHandler(string.Empty);

           Response.Write("<h3>User Control’s Button Click</h3> <BR /> <BR />");
    }
}

now add new item -> web form -> add
Write the following code in the default.aspx


<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>

<%@ Register Src="WebUserControl.ascx" TagName="WebUserControl" TagPrefix="WUC1" %>

<!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>
        <asp:Label ID="lblText" Text="This is On Main Page : " runat="server"></asp:Label>
     
        <asp:DropDownList ID="ddlTemp" runat="server">
            <asp:ListItem>Mahi</asp:ListItem>
            <asp:ListItem>Zoya</asp:ListItem>
            <asp:ListItem>Aditi</asp:ListItem>
        </asp:DropDownList>
     
        <br />
        <br />
        <WUC1:WebUserControl ID="WebUserControl1" runat="server" />
 
    </div>
    </form>
</body>
</html>

save all files and run it in the browser.

No comments:

Post a Comment