65.9K
CodeProject is changing. Read more.
Home

Fire dynamically loaded UserControl event on the page

starIconstarIconstarIconstarIcon
emptyStarIcon
starIcon

4.50/5 (2 votes)

Sep 18, 2012

CPOL
viewsIcon

26520

Load usercontrol dynamically and fire usercontrol's button event on content page.

Introduction

We can add User control on the page by using reference or by dynamically loaded it on the page  in some case we require to fire usercontrol's event like button click on the content page.That we can do using custom event.

here my sample example is how we can fire dynamically loaded user control's button event on the content page. In my simple example I have added a content page and a usercontrol.

In UserControl.ascx,I have added two text box controls, one for "user name" and another for "password" and a login button.

<%@ Control Language="C#" AutoEventWireup="true" 
    CodeFile="MyUserControl.ascx.cs" Inherits="MyUserControl" %>
<table> 
<tr> <td> User Name</td> <td> 

<asp:TextBox ID="txtUserName"runat="server"></asp:TextBox> </td> 
</tr>

<tr> 
<td> Password</td> <td> <asp:TextBox ID="txtPassword" 
   runat="server"></asp:TextBox> </td> </tr> 


<tr>
 <td> </td> <td> <asp:Button ID="btnSave" 
    runat="server" Text="Login" 
    onclick="btnSave_Click" /> </td> </tr> </table> 

MyUserControl.ascx.cs

Declare an event login and subscribe the event on button click

public partial class MyUserControl : System.Web.UI.UserControl
{
    public event EventHandler login;
    protected void Page_Load(object sender, EventArgs e)
    {
    }
    protected void btnSave_Click(object sender, EventArgs e)
    {
        if (login != null)
        {
            login(sender, e);
        }
    }
}

Now "MyUserControl" add on the content page dynamically.

DynamicallyLoadUserControl.aspx

<form id="form1" runat="server">

<div id="divlogin" runat="server">

</div>

</form>

<div id="divlogin" runat="server">

In code behind DynamicallyLoadUserControl.aspx.cs write the below code.

public partial class DynamicallyLoadUserControl : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        var ucon = Page.LoadControl("~/MyUserControl.ascx");
        ucon.ID = "UserControl1";
        dynamic d = ucon;//element that is typed as dynamic is assumed to support any operation
        divlogin.Controls.Add(d);
        d.login += new EventHandler(UserControl1_login);
    }
    void UserControl1_login(object sender, EventArgs e)
    {
        UserControl UserControl1 = (UserControl)Page.FindControl("UserControl1");
        TextBox txt1 = (TextBox)UserControl1.FindControl("txtUserName");
        TextBox txt2 = (TextBox)UserControl1.FindControl("txtPassword");
        Response.Write(string.Format("UserName {0} Passwor {1}", txt1.Text, txt2.Text));
    }
}