Search...

Wednesday, February 8, 2012

How to dynamically add UpdatePanel to asp.net page


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

<!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>How to dynamically add UpdatePanel to asp.net page</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:ScriptManager ID="ScriptManager1" runat="server">
        </asp:ScriptManager>
     
        <asp:Label ID="Label1" runat="server"></asp:Label><br />
        <asp:Label ID="Label2" runat="server"></asp:Label>
     
     </div>
    </form>
</body>
</html>

******************************************************************************


using System;
using System.Web.UI;
public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        Label1.Text = "Date 1 :" + DateTime.Now;
        Label2.Text = "Date 2 :" + DateTime.Now;

        Timer timer = new Timer();
        timer.ID = "Timer1";
        timer.Interval = 1000;
        timer.Tick += new EventHandler<EventArgs>(timer_Tick);

        UpdatePanel updatePanel = new UpdatePanel();
        updatePanel.UpdateMode = UpdatePanelUpdateMode.Conditional;
        updatePanel.ID = "UpdatePanel1";

        updatePanel.ContentTemplateContainer.Controls.Add(Label2);
        updatePanel.ContentTemplateContainer.Controls.Add(timer);

        AsyncPostBackTrigger trigger = new AsyncPostBackTrigger();
        trigger.ControlID = timer.ClientID;
        trigger.EventName = "Tick";

        updatePanel.Triggers.Add(trigger);

        this.Page.Form.Controls.Add(updatePanel);
    }

    protected void timer_Tick(object sender, EventArgs e)
    {
        Label2.Text = "Date 2 :" + DateTime.Now;
    }
}

No comments: