ASP.NET- User control and Page communication
An idea just clicked in my mind, how can a button event handler code from web user control execute method from ASP.NET page.
Action delegate by which I can encapsulates a method from the ASP.NET page and pass that delegate to the User control which will be stored in a delegate variable. In
Page_load
of ASP.NET page, Action delegate variable
getCurrentTime
of the User control will be set using
SetCurrentTimeExecutor
of the user control.
The event handler code from the user control will just run the delegate for example
getCurrentTime()
.
namespace UserControlAndPageCommunication
{
using System;
public partial class CurrentTime : System.Web.UI.UserControl
{
private Action getCurrentTime;
public void SetCurrentTimeExecutor(Action executor)
{
getCurrentTime = executor;
}
protected void btnCurrentTime_Click(object sender, EventArgs e)
{
getCurrentTime();
}
}
}
The above code block is the code behind of the
CurrentTime
web user control. The code behind has a delegate type
Action
which is
getCurrentTime
here.
namespace UserControlAndPageCommunication
{
using System;
public partial class _Default : UserControlAndPageCommunicationBase
{
protected void Page_Load(object sender, EventArgs e)
{
ucCurrentTime.SetCurrentTimeExecutor(DisplayCurrentTime);
}
public void DisplayCurrentTime()
{
txtCurrentTime.Text = base.WhatIsCurrentTime();
}
}
}
So now when the
btnCurrentTime_Click
event handler will fire, then it will execute
getCurrentTime
delegate eventually it will execute
DisplayCurrentTime()
from the Default page.
DisplayCurrentTime
will call
WhatIsCurrentTime
from the base class. Base class contains:
namespace UserControlAndPageCommunication
{
using System;
using System.Web.UI;
public class UserControlAndPageCommunicationBase : Page
{
public string WhatIsCurrentTime()
{
return DateTime.Now.TimeOfDay.ToString();
}
}
}
The HTML contents of the page and user control are:
<%@ Page Title="Home Page" Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs"
Inherits="UserControlAndPageCommunication._Default" %>
<%@ Register Src="CurrentTime.ascx" TagName="CurrentTime" TagPrefix="UserControl" %>
<html>
<head>
<title></title>
</head>
<body>
<form id="frmMain" runat="server">
<fieldset>
<legend>User Control and Page communication</legend>Current time
<asp:TextBox ID="txtCurrentTime" runat="server"></asp:TextBox>
<UserControl:CurrentTime ID="ucCurrentTime" runat="server" />
</fieldset>
</form>
</body>
</html>
and user control:
<%@ Control Language="C#" AutoEventWireup="true" CodeBehind="CurrentTime.ascx.cs"
Inherits="UserControlAndPageCommunication.CurrentTime" %>
<div>
To get current time, please click on the following button
<asp:Button ID="btnCurrentTime" runat="server" Text="Current Time"
onclick="btnCurrentTime_Click" />
</div>