UpdatePanel Control Overview

ASP.NET UpdatePanel controls enable you to build rich, client-centric Web applications. By using UpdatePanel controls, you can refresh selected parts of the page instead of refreshing the whole page with a postback. This is referred to as performing a partial-page update. An ASP.NET Web page that contains a ScriptManager control and one or more UpdatePanel controls can automatically participate in partial-page updates, without custom client script.

This topic contains information about the following:

  • Scenarios

  • Background

  • Code Examples

  • Class Reference

Scenarios

The UpdatePanel control is a server control that helps you develop Web pages with complex client behavior that makes a Web page appear more interactive to the end user. Writing code that coordinates between server and client to update only specified parts of a Web page usually requires in-depth knowledge of ECMAScript (JavaScript). However, by using the UpdatePanel control, you can enable a Web page to participate in partial-page updates without writing any client script. If you want, you can add custom client script to enhance the client user experience. When you use an UpdatePanel control, the page behavior is browser independent and can potentially reduce the amount of data that is transferred between client and server.

Background

UpdatePanel controls work by specifying regions of a page that can be updated without refreshing the whole page. This process is coordinated by the ScriptManager server control and the client PageRequestManager class. When partial-page updates are enabled, controls can asynchronously post to the server. An asynchronous postback behaves like a regular postback in that the resulting server page executes the complete page and control life cycle. However, with an asynchronous postback, page updates are limited to regions of the page that are enclosed in UpdatePanel controls and that are marked to be updated. The server sends HTML markup for only the affected elements to the browser. In the browser, the client PageRequestManager class performs Document Object Model (DOM) manipulation to replace existing HTML with updated markup.

Note

When you are using asynchronous postbacks or using the XMLHTTPRequest object, a postback error can occur if the URL contains a double-byte character. You can resolve this problem by including a <base href="url"/> element in the head element of the page, where the href attribute is set to the URL-encoded string that references the page. You can add this element added dynamically in server code.

The following illustration shows a page that is loaded for the first time, and a subsequent asynchronous postback that refreshes the content of an UpdatePanel control.

Partial-page rendering overview

Partial-Page Rendering Overview

Enabling Partial-Page Updates

The UpdatePanel control requires a ScriptManager control in the Web page. By default, partial-page updates are enabled because the default value of the EnablePartialRendering property of the ScriptManager control is true.

The following example shows markup that defines a ScriptManager control and an UpdatePanel control on a page. The UpdatePanel control contains a Button control that refreshes the content inside the panel when you click it. By default, the ChildrenAsTriggers property is true. Therefore, the Button control acts as an asynchronous postback control.

<asp:ScriptManager ID="ScriptManager" 
                   runat="server" />
<asp:UpdatePanel ID="UpdatePanel1" 
                 UpdateMode="Conditional"
                 runat="server">
    <ContentTemplate>
       <fieldset>
       <legend>UpdatePanel content</legend>
        <!-- Other content in the panel. -->
        <%=DateTime.Now.ToString() %>
        <br />
        <asp:Button ID="Button1" 
                    Text="Refresh Panel" 
                    runat="server" />
        </fieldset>
    </ContentTemplate>
</asp:UpdatePanel>
<asp:ScriptManager ID="ScriptManager" 
                   runat="server" />
<asp:UpdatePanel ID="UpdatePanel1" 
                 UpdateMode="Conditional"
                 runat="server">
    <ContentTemplate>
       <fieldset>
       <legend>UpdatePanel content</legend>
        <!-- Other content in the panel. -->
        <%=DateTime.Now.ToString() %>
        <br />
        <asp:Button ID="Button1" 
                    Text="Refresh Panel" 
                    runat="server" />
        </fieldset>
    </ContentTemplate>
</asp:UpdatePanel>

Specifying UpdatePanel Control Content

You add content to an UpdatePanel control declaratively or in the designer by using the ContentTemplate property. In markup, this property is exposed as a ContentTemplate element. To add content programmatically, you use the ContentTemplateContainer property.

When a page that contains one or more UpdatePanel controls is first rendered, all the contents of the UpdatePanel controls are rendered and sent to the browser. On subsequent asynchronous postbacks, the content of individual UpdatePanel controls might be updated. Updates depend on the panel settings, on what element caused the postback, and on code that is specific to each panel.

Specifying UpdatePanel Triggers

By default, any postback control inside an UpdatePanel control causes an asynchronous postback and refreshes the panel's content. However, you can also configure other controls on the page to refresh an UpdatePanel control. You do this by defining a trigger for the UpdatePanel control. A trigger is a binding that specifies which postback control and event cause a panel to update. When the specified event of the trigger control is raised (for example, a button's Click event), the update panel is refreshed.

The following example shows how to specify a trigger for an UpdatePanel control.

<asp:Button ID="Button1" 
            Text="Refresh Panel"
            runat="server" />
<asp:ScriptManager ID="ScriptManager1" 
                   runat="server" />
<asp:UpdatePanel ID="UpdatePanel1" 
                 UpdateMode="Conditional"
                 runat="server">
                 <Triggers>
                   <asp:AsyncPostBackTrigger ControlID="Button1" />
                 </Triggers>
                 <ContentTemplate>
                 <fieldset>
                 <legend>UpdatePanel content</legend>
                 <%=DateTime.Now.ToString() %>
                 </fieldset>
                 </ContentTemplate>
</asp:UpdatePanel>
<asp:Button ID="Button1" 
            Text="Refresh Panel"
            runat="server" />
<asp:ScriptManager ID="ScriptManager1" 
                   runat="server" />
<asp:UpdatePanel ID="UpdatePanel1" 
                 UpdateMode="Conditional"
                 runat="server">
                 <Triggers>
                   <asp:AsyncPostBackTrigger ControlID="Button1" />
                 </Triggers>
                 <ContentTemplate>
                 <fieldset>
                 <legend>UpdatePanel content</legend>
                 <%=DateTime.Now.ToString() %>
                 </fieldset>
                 </ContentTemplate>
</asp:UpdatePanel>

The trigger is defined by using the asp:AsyncPostBackTrigger element inside the Triggers element of the UpdatePanel control. (If you are editing the page in Visual Studio, you can create triggers by using the UpdatePanelTrigger Collection Editor dialog box.)

A trigger's control event is optional. If you do not specify an event, the trigger event is the default event of the control. For example, for the Button control, the default event is the Click event.

How UpdatePanel Controls Are Refreshed

The following list describes the property settings of the UpdatePanel control that determine when a panel's content is updated during partial-page rendering.

  • If the UpdateMode property is set to Always, the UpdatePanel control’s content is updated on every postback that originates from anywhere on the page. This includes asynchronous postbacks from controls that are inside other UpdatePanel controls, and postbacks from controls that are not inside UpdatePanel controls.

  • If the UpdateMode property is set to Conditional, the UpdatePanel control’s content is updated when one of the following is true:

    • When the postback is caused by a trigger for that UpdatePanel control.

    • When you explicitly call the UpdatePanel control's Update method.

    • When the UpdatePanel control is nested inside another UpdatePanel control and the parent panel is updated.

    • When the ChildrenAsTriggers property is set to true and any child control of the UpdatePanel control causes a postback. Child controls of nested UpdatePanel controls do not cause an update to the outer UpdatePanel control unless they are explicitly defined as triggers for the parent panel.

If the ChildrenAsTriggers property is set to false and the UpdateMode property is set to Always, an exception is thrown. The ChildrenAsTriggers property is intended to be used only when the UpdateMode property is set to Conditional.

Using UpdatePanel Controls in Master Pages

To use an UpdatePanel control in a master page, you must decide how to include the ScriptManager control. If you include the ScriptManager control on the master page, it can act as the ScriptManager control for all content pages. (If you want to register scripts or services declaratively in a content page, you can add a ScriptManagerProxy control to that content page.)

If the master page does not contain the ScriptManager control, you can put the ScriptManager control individually on each content page that contains an UpdatePanel control. The design choice depends on how you intend to manage client script in your application. For more information about how to manage client script, see ScriptManager Control Overview. For more information about master pages, see ASP.NET Master Pages Overview.

In some cases, the ScriptManager control is on the master page and you do not need partial-page rendering capabilities for a content page. In those cases, you must programmatically set the EnablePartialRendering property of the ScriptManager control to false for that content page.

The following example shows markup for a ScriptManager control on the master page and an UpdatePanel control on a content page. In this example, a property named LastUpdate is defined on the master page and is referenced from inside the UpdatePanel control.

<%@ Master Language="VB" %>
<!DOCTYPE html PUBLIC "-'W3C'DTD XHTML 1.0 Transitional'EN"
 "http:'www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<script runat="server">

    Public Property LastUpdate() As DateTime
        Get
            If ViewState("LastUpdate") Is Nothing Then
                Return DateTime.Now
            Else : Return ViewState("LastUpdate")
            End If
        End Get
        Set(ByVal value As DateTime)
            ViewState("LastUpdate") = value
        End Set
    End Property

    Protected Sub MasterButton2_Click(ByVal Sender As Object, ByVal E As EventArgs)
        LastUpdate = DateTime.Now
        Dim up1 As UpdatePanel
        up1 = ContentPlaceHolder1.FindControl("UpdatePanel1")
        up1.Update()

    End Sub
    
    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs)
        ScriptManager1.RegisterAsyncPostBackControl(Button2)
    End Sub
</script>

<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
    <title>ScriptManager in Master Page Example</title>
</head>
<body>
    <form id="form1" runat="server">
        <div>
            <asp:ScriptManager ID="ScriptManager1" runat="server" />
            <asp:Panel ID="MasterPanel1" runat="server" GroupingText="Master Page">
               <asp:Button ID="Button1" runat="server" Text="Full Page Refresh" />
               <asp:Button ID="Button2" runat="server" Text="Refresh Panel" OnClick="MasterButton2_Click" />
            </asp:Panel>
            <asp:ContentPlaceHolder ID="ContentPlaceHolder1" runat="server">
            </asp:ContentPlaceHolder>
        </div>
    </form>
</body>
</html>
<%@ Master Language="C#" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<script runat="server">

    public DateTime LastUpdate
    {
        get
        {
            return (DateTime)(ViewState["LastUpdate"] ?? DateTime.Now);
        }
        set
        {
            ViewState["LastUpdate"] = value;
        }
    }


    protected void MasterButton2_Click(object sender, EventArgs e)
    {
        LastUpdate = DateTime.Now;
        ((UpdatePanel)ContentPlaceHolder1.FindControl("UpdatePanel1")).Update();

    }

    protected void Page_Load(object sender, EventArgs e)
    {
        ScriptManager1.RegisterAsyncPostBackControl(Button2);
    }
</script>

<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
    <title>ScriptManager in Master Page Example</title>
</head>
<body>
    <form id="form1" runat="server">
        <div>
            <asp:ScriptManager ID="ScriptManager1" runat="server" />
            <asp:Panel ID="MasterPanel1" runat="server" GroupingText="Master Page">
               <asp:Button ID="Button1" runat="server" Text="Full Page Refresh" />
               <asp:Button ID="Button2" runat="server" Text="Refresh Panel" OnClick="MasterButton2_Click" />
            </asp:Panel>
            <asp:ContentPlaceHolder ID="ContentPlaceHolder1" runat="server">
            </asp:ContentPlaceHolder>
        </div>
    </form>
</body>
</html>
<%@ Page Language="VB" MasterPageFile="MasterVB.master"
    Title="ScriptManager in Content Page" %>

<%@ MasterType VirtualPath="MasterVB.master" %>

<script runat="server">

    Protected Sub Button3_Click(ByVal Sender As Object, ByVal E As EventArgs)
       Master.LastUpdate = DateTime.Now
    End Sub

</script>

<asp:Content ID="Content1" ContentPlaceHolderID="ContentPlaceHolder1"
    runat="Server">
    </asp:ScriptManagerProxy>
    <asp:Panel ID="Panel2"
               GroupingText="ContentPage"
               runat="server" >
        <asp:UpdatePanel ID="UpdatePanel1" 
                         UpdateMode="Conditional" 
                         runat="server">
            <ContentTemplate>
                <p>
                    Last updated: <strong>
                        <%= Master.LastUpdate.ToString() %>
                    </strong>
                </p>
                <asp:Button ID="Button3"
                            Text="Refresh Panel"
                            OnClick="Button3_Click"
                            runat="server"  />
            </ContentTemplate>
        </asp:UpdatePanel>
    </asp:Panel>
</asp:Content>
<%@ Page Language="C#" MasterPageFile="MasterCS.master"
    Title="ScriptManager in Content Page" %>

<%@ MasterType VirtualPath="MasterCS.master" %>

<script runat="server">

    protected void Button3_Click(object sender, EventArgs e)
    {
        Master.LastUpdate = DateTime.Now;
    }

</script>

<asp:Content ID="Content1" ContentPlaceHolderID="ContentPlaceHolder1"
    runat="Server">
    <asp:Panel ID="Panel2"
               GroupingText="ContentPage"
               runat="server" >
        <asp:UpdatePanel ID="UpdatePanel1" 
                         UpdateMode="Conditional" 
                         runat="server">
            <ContentTemplate>
                <p>
                    Last updated: <strong>
                        <%= Master.LastUpdate.ToString() %>
                    </strong>
                </p>
                <asp:Button ID="Button3"
                            Text="Refresh Panel"
                            OnClick="Button3_Click"
                            runat="server"  />
            </ContentTemplate>
        </asp:UpdatePanel>
    </asp:Panel>
</asp:Content>

Using Nested UpdatePanel Controls

UpdatePanel controls can be nested. If the parent panel is refreshed, all nested panels are refreshed also.

The following example shows markup that defines an UpdatePanel control inside another UpdatePanel control. A button in the parent panel triggers an update of the content in both the parent and the child panel. The button in the child panel triggers an update of only the child panel.

<%@ Page Language="VB" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 
 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<script runat="server">
</script>

<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
    <title>UpdatePanelUpdateMode Example</title>
    <style type="text/css">
    div.NestedPanel
    {
      position: relative;
      margin: 2% 5% 2% 5%;
    }
    </style>
</head>
<body>
    <form id="form1" runat="server">
        <div>
            <asp:ScriptManager ID="ScriptManager" 
                               runat="server" />
            <asp:UpdatePanel ID="OuterPanel" 
                             UpdateMode="Conditional" 
                             runat="server">
                <ContentTemplate>
                    <div>
                        <fieldset>
                            <legend>Outer Panel </legend>
                            <br />
                            <asp:Button ID="OPButton1" 
                                        Text="Outer Panel Button" 
                                        runat="server" />
                            <br />
                            Last updated on
                            <%= DateTime.Now.ToString() %>
                            <br />
                            <br />
                            <asp:UpdatePanel ID="NestedPanel1" 
                                               UpdateMode="Conditional"
                                               runat="server">
                                <ContentTemplate>
                                    <div class="NestedPanel">
                                        <fieldset>
                                            <legend>Nested Panel 1</legend>
                                            <br />
                                            Last updated on
                                            <%= DateTime.Now.ToString() %>
                                            <br />
                                            <asp:Button ID="NPButton1"
                                                        Text="Nested Panel 1 Button" 
                                                        runat="server" />
                                        </fieldset>
                                    </div>
                                </ContentTemplate>
                            </asp:UpdatePanel>
                        </fieldset>
                    </div>
                </ContentTemplate>
            </asp:UpdatePanel>
        </div>
    </form>
</body>
</html>
<%@ Page Language="C#" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<script runat="server">
</script>

<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
    <title>UpdatePanelUpdateMode Example</title>
    <style type="text/css">
    div.NestedPanel
    {
      position: relative;
      margin: 2% 5% 2% 5%;
    }
    </style>
</head>
<body>
    <form id="form1" runat="server">
        <div>
            <asp:ScriptManager ID="ScriptManager" 
                               runat="server" />
            <asp:UpdatePanel ID="OuterPanel" 
                             UpdateMode="Conditional" 
                             runat="server">
                <ContentTemplate>
                    <div>
                        <fieldset>
                            <legend>Outer Panel </legend>
                            <br />
                            <asp:Button ID="OPButton1" 
                                        Text="Outer Panel Button" 
                                        runat="server" />
                            <br />
                            Last updated on
                            <%= DateTime.Now.ToString() %>
                            <br />
                            <br />
                            <asp:UpdatePanel ID="NestedPanel1" 
                                               UpdateMode="Conditional"
                                               runat="server">
                                <ContentTemplate>
                                    <div class="NestedPanel">
                                        <fieldset>
                                            <legend>Nested Panel 1</legend>
                                            <br />
                                            Last updated on
                                            <%= DateTime.Now.ToString() %>
                                            <br />
                                            <asp:Button ID="NPButton1"
                                                        Text="Nested Panel 1 Button" 
                                                        runat="server" />
                                        </fieldset>
                                    </div>
                                </ContentTemplate>
                            </asp:UpdatePanel>
                        </fieldset>
                    </div>
                </ContentTemplate>
            </asp:UpdatePanel>
        </div>
    </form>
</body>
</html>

The following example shows a nested UpdatePanel control with a GridView control. The GridView control is inside an UpdatePanel control, and each GridView row contains a nested GridView control inside another UpdatePanel control.

<%@ Page Language="VB" %>

<!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>Browse Departments</title>
    <script runat="server">
        Protected Sub DepartmentsGridView_RowDataBound(sender As object, e As GridViewRowEventArgs)
            If e.Row.RowType = DataControlRowType.DataRow Then
                Dim s As SqlDataSource = CType(e.Row.FindControl("EmployeesDataSource"), SqlDataSource)
                Dim r As System.Data.DataRowView = CType(e.Row.DataItem, System.Data.DataRowView)
                s.SelectParameters("DepartmentID").DefaultValue = r("DepartmentID").ToString()
            End If
        End Sub
    </script>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:ScriptManager runat="server" ID="ScriptManager1" EnablePartialRendering="true" />
        <asp:UpdatePanel ID="UpdatePanel2" runat="server" UpdateMode="Conditional">
            <ContentTemplate>
        <asp:GridView ID="DepartmentsGridView" runat="server" AllowPaging="True" AllowSorting="True"
            AutoGenerateColumns="False" CellPadding="4" DataSourceID="DepartmentDataSource"
            ForeColor="#333333" GridLines="None" PageSize="3" OnRowDataBound="DepartmentsGridView_RowDataBound">
            <FooterStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
            <Columns>
                <asp:BoundField DataField="GroupName" HeaderText="Division" SortExpression="GroupName" >
                    <ItemStyle Width="200px" />
                </asp:BoundField>
                <asp:BoundField DataField="Name" HeaderText="Department Name" SortExpression="Name" >
                    <ItemStyle Width="160px" />
                </asp:BoundField>
                <asp:TemplateField HeaderText="Employees">
                    <ItemTemplate>
                        <asp:UpdatePanel ID="UpdatePanel1" runat="server" UpdateMode="Conditional">
                            <ContentTemplate>
                                <asp:GridView ID="EmployeesGridView" runat="server" AllowPaging="True" AllowSorting="True"
                                    AutoGenerateColumns="False" BackColor="White" BorderColor="#999999" BorderStyle="None"
                                    BorderWidth="1px" CellPadding="3" DataSourceID="EmployeesDataSource" GridLines="Vertical"
                                    PageSize="4">
                                    <FooterStyle BackColor="#CCCCCC" ForeColor="Black" />
                                    <Columns>
                                        <asp:BoundField DataField="FirstName" HeaderText="First Name" SortExpression="FirstName" >
                                            <ItemStyle Width="80px" />
                                        </asp:BoundField>
                                        <asp:BoundField DataField="LastName" HeaderText="Last Name" SortExpression="LastName" >
                                            <ItemStyle Width="160px" />
                                        </asp:BoundField>
                                    </Columns>
                                    <RowStyle BackColor="#EEEEEE" ForeColor="Black" />
                                    <SelectedRowStyle BackColor="#008A8C" Font-Bold="True" ForeColor="White" />
                                    <PagerStyle BackColor="#999999" ForeColor="Black" HorizontalAlign="Center" />
                                    <HeaderStyle BackColor="#000084" Font-Bold="True" ForeColor="White" />
                                    <AlternatingRowStyle BackColor="Gainsboro" />
                                </asp:GridView>
                                <asp:Label runat="server" ID="InnerTimeLabel"><%=DateTime.Now %></asp:Label>
                                <asp:SqlDataSource ID="EmployeesDataSource" runat="server" ConnectionString="<%$ ConnectionStrings:AdventureWorksConnectionString %>"
                                    SelectCommand="SELECT HumanResources.EmployeeDepartmentHistory.DepartmentID, 
                                                          HumanResources.vEmployee.EmployeeID, 
                                                          HumanResources.vEmployee.FirstName, 
                                                          HumanResources.vEmployee.LastName 
                                                   FROM HumanResources.EmployeeDepartmentHistory
                                                   INNER JOIN HumanResources.vEmployee 
                                                     ON HumanResources.EmployeeDepartmentHistory.EmployeeID = HumanResources.vEmployee.EmployeeID
                                                   WHERE HumanResources.EmployeeDepartmentHistory.DepartmentID = @DepartmentID
                                                   ORDER BY HumanResources.vEmployee.LastName ASC, HumanResources.vEmployee.FirstName ASC">
                                    <SelectParameters>
                                      <asp:Parameter Name="DepartmentID" DefaultValue="0" Type="int32" />
                                    </SelectParameters>
                                </asp:SqlDataSource>
                            </ContentTemplate>
                        </asp:UpdatePanel>
                    </ItemTemplate>
                    <ItemStyle Height="170px" Width="260px" />
                </asp:TemplateField>
            </Columns>
            <RowStyle BackColor="#F7F6F3" ForeColor="#333333" VerticalAlign="Top" />
            <EditRowStyle BackColor="#999999" />
            <SelectedRowStyle BackColor="#E2DED6" Font-Bold="True" ForeColor="#333333" />
            <PagerStyle BackColor="#284775" ForeColor="White" HorizontalAlign="Center" />
            <HeaderStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" HorizontalAlign="Left" />
            <AlternatingRowStyle BackColor="White" ForeColor="#284775" VerticalAlign="Top" />
        </asp:GridView>
        <asp:Label runat="server" ID="OuterTimeLabel"><%=DateTime.Now %></asp:Label>
            </ContentTemplate>
        </asp:UpdatePanel>
        &nbsp;
        <asp:SqlDataSource ID="DepartmentDataSource" runat="server" ConnectionString="<%$ ConnectionStrings:AdventureWorksConnectionString %>"
            SelectCommand="SELECT DepartmentID, Name, GroupName FROM HumanResources.Department ORDER BY Name">
        </asp:SqlDataSource>

    </div>
    </form>
</body>
</html>
<%@ Page Language="C#" %>

<!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>Browse Departments</title>
    <script runat="server">
        protected void DepartmentsGridView_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                SqlDataSource s = (SqlDataSource)e.Row.FindControl("EmployeesDataSource");
                System.Data.DataRowView r = (System.Data.DataRowView)e.Row.DataItem;
                s.SelectParameters["DepartmentID"].DefaultValue = r["DepartmentID"].ToString();
            }
        }
    </script>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:ScriptManager runat="server" ID="ScriptManager1" EnablePartialRendering="true" />
        <asp:UpdatePanel ID="UpdatePanel2" runat="server" UpdateMode="Conditional">
            <ContentTemplate>
        <asp:GridView ID="DepartmentsGridView" runat="server" AllowPaging="True" AllowSorting="True"
            AutoGenerateColumns="False" CellPadding="4" DataSourceID="DepartmentDataSource"
            ForeColor="#333333" GridLines="None" PageSize="3" OnRowDataBound="DepartmentsGridView_RowDataBound">
            <FooterStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
            <Columns>
                <asp:BoundField DataField="GroupName" HeaderText="Division" SortExpression="GroupName" >
                    <ItemStyle Width="200px" />
                </asp:BoundField>
                <asp:BoundField DataField="Name" HeaderText="Department Name" SortExpression="Name" >
                    <ItemStyle Width="160px" />
                </asp:BoundField>
                <asp:TemplateField HeaderText="Employees">
                    <ItemTemplate>
                        <asp:UpdatePanel ID="UpdatePanel1" runat="server" UpdateMode="Conditional">
                            <ContentTemplate>
                                <asp:GridView ID="EmployeesGridView" runat="server" AllowPaging="True" AllowSorting="True"
                                    AutoGenerateColumns="False" BackColor="White" BorderColor="#999999" BorderStyle="None"
                                    BorderWidth="1px" CellPadding="3" DataSourceID="EmployeesDataSource" GridLines="Vertical"
                                    PageSize="4">
                                    <FooterStyle BackColor="#CCCCCC" ForeColor="Black" />
                                    <Columns>
                                        <asp:BoundField DataField="FirstName" HeaderText="First Name" SortExpression="FirstName" >
                                            <ItemStyle Width="80px" />
                                        </asp:BoundField>
                                        <asp:BoundField DataField="LastName" HeaderText="Last Name" SortExpression="LastName" >
                                            <ItemStyle Width="160px" />
                                        </asp:BoundField>
                                    </Columns>
                                    <RowStyle BackColor="#EEEEEE" ForeColor="Black" />
                                    <SelectedRowStyle BackColor="#008A8C" Font-Bold="True" ForeColor="White" />
                                    <PagerStyle BackColor="#999999" ForeColor="Black" HorizontalAlign="Center" />
                                    <HeaderStyle BackColor="#000084" Font-Bold="True" ForeColor="White" />
                                    <AlternatingRowStyle BackColor="Gainsboro" />
                                </asp:GridView>
                                <asp:Label runat="server" ID="InnerTimeLabel"><%=DateTime.Now %></asp:Label>
                                <asp:SqlDataSource ID="EmployeesDataSource" runat="server" ConnectionString="<%$ ConnectionStrings:AdventureWorksConnectionString %>"
                                    SelectCommand="SELECT HumanResources.EmployeeDepartmentHistory.DepartmentID, 
                                                          HumanResources.vEmployee.EmployeeID, 
                                                          HumanResources.vEmployee.FirstName, 
                                                          HumanResources.vEmployee.LastName 
                                                   FROM HumanResources.EmployeeDepartmentHistory
                                                   INNER JOIN HumanResources.vEmployee 
                                                     ON HumanResources.EmployeeDepartmentHistory.EmployeeID = HumanResources.vEmployee.EmployeeID
                                                   WHERE HumanResources.EmployeeDepartmentHistory.DepartmentID = @DepartmentID
                                                   ORDER BY HumanResources.vEmployee.LastName ASC, HumanResources.vEmployee.FirstName ASC">
                                    <SelectParameters>
                                      <asp:Parameter Name="DepartmentID" DefaultValue="0" Type="int32" />
                                    </SelectParameters>
                                </asp:SqlDataSource>
                            </ContentTemplate>
                        </asp:UpdatePanel>
                    </ItemTemplate>
                    <ItemStyle Height="170px" Width="260px" />
                </asp:TemplateField>
            </Columns>
            <RowStyle BackColor="#F7F6F3" ForeColor="#333333" VerticalAlign="Top" />
            <EditRowStyle BackColor="#999999" />
            <SelectedRowStyle BackColor="#E2DED6" Font-Bold="True" ForeColor="#333333" />
            <PagerStyle BackColor="#284775" ForeColor="White" HorizontalAlign="Center" />
            <HeaderStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" HorizontalAlign="Left" />
            <AlternatingRowStyle BackColor="White" ForeColor="#284775" VerticalAlign="Top" />
        </asp:GridView>
        <asp:Label runat="server" ID="OuterTimeLabel"><%=DateTime.Now %></asp:Label>
            </ContentTemplate>
        </asp:UpdatePanel>
        &nbsp;
        <asp:SqlDataSource ID="DepartmentDataSource" runat="server" ConnectionString="<%$ ConnectionStrings:AdventureWorksConnectionString %>"
            SelectCommand="SELECT DepartmentID, Name, GroupName FROM HumanResources.Department ORDER BY Name">
        </asp:SqlDataSource>

    </div>
    </form>
</body>
</html>

When an inner GridView control displays a new page of records, the outer panel and the panels in the other rows of the outer GridView control are not refreshed. When the outer GridView control displays a new page of records, the outer panel and the nested panels are all refreshed.

Refreshing an UpdatePanel Programmatically

The following example shows how to refresh an UpdatePanel control programmatically. In this example, a page registers a control as a trigger by calling the RegisterAsyncPostBackControl method. The code refreshes the UpdatePanel control programmatically by calling the Update method.

<%@ Page Language="VB" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<script runat="server">

    Protected Property AnsweredQuestions As SortedList
        Get
            If ViewState("AnsweredQuestions") IsNot Nothing Then
                Return CType(ViewState("AnsweredQuestions"), SortedList)
            Else 
                Return New SortedList()
            End If
        End Get
        Set
          ViewState("AnsweredQuestions") = value
        End Set
    End Property

    Protected Sub Page_Load()
        ScriptManager1.RegisterAsyncPostBackControl(SurveyDataList)
    End Sub

    Protected Sub ChoicesRadioButtonList_SelectedIndexChanged(sender As Object, e As EventArgs)
        Dim answers As SortedList = Me.AnsweredQuestions
        Dim r As RadioButtonList = CType(sender, RadioButtonList)
        answers(r.ToolTip) = r.SelectedValue
        Me.AnsweredQuestions = answers

        ResultsList.DataSource = Me.AnsweredQuestions
        ResultsList.DataBind()

        If Me.AnsweredQuestions.Count = SurveyDataList.Items.Count Then _
            SubmitButton.Visible = True

        UpdatePanel1.Update()
    End Sub

    Protected Sub SubmitButton_Click(sender As Object, e As EventArgs)
        ' Submit responses.
    End Sub
</script>

<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
    <title>Registering Controls as Async Postback Controls</title>
    <style type="text/css">
    .AnswerFloatPanelStyle {
    background-color: bisque;
    position: absolute;
    right: 10px;
    height: 130px;
    width: 150px;
    border-right: silver thin solid; border-top: silver thin solid; 
    border-left: silver thin solid; border-bottom: silver thin solid;    
    }
    </style>
</head>
<body>
    <form id="form1" runat="server">
        <div>
            <asp:ScriptManager ID="ScriptManager1" runat="server" />
            <div id="AnswerFloatPanel" class="AnswerFloatPanelStyle" runat="server">
                <asp:UpdatePanel ID="UpdatePanel1" UpdateMode="Conditional" runat="server">
                    <ContentTemplate>
                        Completed Questions:
                        <asp:DataList ID="ResultsList" runat="server">
                            <ItemTemplate>
                                <asp:Label ID="ResultQuestion" runat="server" Text='<%# Eval("Key") %>' />
                                ::
                                <asp:Label ID="ResultAnswer" runat="server" Text='<%# Eval("Value") %>' />
                            </ItemTemplate>
                        </asp:DataList>
                        <p style="text-align: right">
                            <asp:Button ID="SubmitButton" Text="Submit" runat="server" Visible="false"
                                OnClick="SubmitButton_Click" />
                        </p>
                        <asp:Label ID="Message" runat="Server" />
                    </ContentTemplate>
                </asp:UpdatePanel>
            </div>

            <asp:XmlDataSource ID="SurveyDataSource" 
                               runat="server" 
                               XPath="/Questions/Question"
                               DataFile="~/App_Data/SurveyQuestions.xml"/>
            <asp:DataList
                ID="SurveyDataList"
                DataSourceID="SurveyDataSource"
                runat="server">

                <ItemTemplate>
                  <table cellpadding="2" cellspacing="2">
                    <tr>
                      <td valign="top">
                        <asp:Label id="QuestionLabel" Text='<%# XPath("@Title")%>' runat="server" />
                      </td>
                    </tr>
                    <tr><td>
                      <asp:RadioButtonList ID="ChoicesRadioButtonList" runat="server" 
                        DataSource='<%#XPathSelect("Choices/Choice") %>'
                        DataTextField="InnerText" DataValueField="InnerText" 
                        AutoPostBack="True"
                        ToolTip='<%# "Question" + XPath("@ID") %>'
                        OnSelectedIndexChanged="ChoicesRadioButtonList_SelectedIndexChanged"/>
                    </td></tr>
                  </table>

                  <hr />
                </ItemTemplate>
            </asp:DataList>
        </div>
    </form>
</body>
</html>
<%@ Page Language="C#" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<script runat="server">

    protected SortedList AnsweredQuestions
    {
        get { return (SortedList)(ViewState["AnsweredQuestions"] ?? new SortedList()); }
        set { ViewState["AnsweredQuestions"] = value; }
    }

    protected void Page_Load()
    {
        ScriptManager1.RegisterAsyncPostBackControl(SurveyDataList);
    }

    protected void ChoicesRadioButtonList_SelectedIndexChanged(object sender, EventArgs e)
    {
        SortedList answers = this.AnsweredQuestions;
        RadioButtonList r = (RadioButtonList)sender;
        answers[r.ToolTip] = r.SelectedValue;
        this.AnsweredQuestions = answers;

        ResultsList.DataSource = this.AnsweredQuestions;
        ResultsList.DataBind();

        if (this.AnsweredQuestions.Count == SurveyDataList.Items.Count)
            SubmitButton.Visible = true;

        UpdatePanel1.Update();
    }

    protected void SubmitButton_Click(object sender, EventArgs e)
    {
        // Submit responses.
    }
</script>

<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
    <title>Registering Controls as Async Postback Controls</title>
    <style type="text/css">
    .AnswerFloatPanelStyle {
    background-color: bisque;
    position: absolute;
    right: 10px;
    height: 130px;
    width: 150px;
    border-right: silver thin solid; border-top: silver thin solid; 
    border-left: silver thin solid; border-bottom: silver thin solid;    
    }
    </style>
</head>
<body>
    <form id="form1" runat="server">
        <div>
            <asp:ScriptManager ID="ScriptManager1" runat="server" />
            <div id="AnswerFloatPanel" class="AnswerFloatPanelStyle" runat="server">
                <asp:UpdatePanel ID="UpdatePanel1" UpdateMode="Conditional" runat="server">
                    <ContentTemplate>
                        Completed Questions:
                        <asp:DataList ID="ResultsList" runat="server">
                            <ItemTemplate>
                                <asp:Label ID="ResultQuestion" runat="server" Text='<%# Eval("Key") %>' />
                                ::
                                <asp:Label ID="ResultAnswer" runat="server" Text='<%# Eval("Value") %>' />
                            </ItemTemplate>
                        </asp:DataList>
                        <p style="text-align: right">
                            <asp:Button ID="SubmitButton" Text="Submit" runat="server" Visible="false"
                                OnClick="SubmitButton_Click" />
                        </p>
                        <asp:Label ID="Message" runat="Server" />
                    </ContentTemplate>
                </asp:UpdatePanel>
            </div>

            <asp:XmlDataSource ID="SurveyDataSource" 
                               runat="server" 
                               XPath="/Questions/Question"
                               DataFile="~/App_Data/SurveyQuestions.xml"/>
            <asp:DataList
                ID="SurveyDataList"
                DataSourceID="SurveyDataSource"
                runat="server">

                <ItemTemplate>
                  <table cellpadding="2" cellspacing="2">
                    <tr>
                      <td valign="top">
                        <asp:Label id="QuestionLabel" Text='<%# XPath("@Title")%>' runat="server" />
                      </td>
                    </tr>
                    <tr><td>
                      <asp:RadioButtonList ID="ChoicesRadioButtonList" runat="server" 
                        DataSource='<%#XPathSelect("Choices/Choice") %>'
                        DataTextField="InnerText" DataValueField="InnerText" 
                        AutoPostBack="True"
                        ToolTip='<%# "Question" + XPath("@ID") %>'
                        OnSelectedIndexChanged="ChoicesRadioButtonList_SelectedIndexChanged"/>
                    </td></tr>
                  </table>

                  <hr />
                </ItemTemplate>
            </asp:DataList>
        </div>
    </form>
</body>
</html>

Creating UpdatePanel Controls Programmatically

To add an UpdatePanel control to a page programmatically, you create a new instance of the UpdatePanel control. You then add controls to it by using the ContentTemplateContainer property and the ControlCollection.Add method. Do not add controls directly to the ContentTemplate property.

When an UpdatePanel control is added programmatically, only postbacks that are from controls in the same naming container as the UpdatePanel control can be used as triggers for the panel.

The following example shows how to programmatically add an UpdatePanel control to a page. The example adds a Label and a Button control to the panel by using the ContentTemplateContainer property. Because the ChildrenAsTriggers property is true by default, the Button control acts as a trigger for the panel.

<%@ Page Language="VB" %>

<!DOCTYPE html PUBLIC "-'W3C'DTD XHTML 1.0 Transitional'EN" 
 "http:'www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<script runat="server">

    Protected Sub Page_Load(ByVal Sender As Object, ByVal E As EventArgs)
        Dim up1 As UpdatePanel
        up1 = New UpdatePanel()
        up1.ID = "UpdatePanel1"
        up1.UpdateMode = UpdatePanelUpdateMode.Conditional
        Dim button1 As Button
        button1 = New Button()
        button1.ID = "Button1"
        button1.Text = "Submit"
        AddHandler button1.Click, AddressOf Button_Click
        Dim label1 As Label
        label1 = New Label()
        label1.ID = "Label1"
        label1.Text = "A full page postback occurred."
        up1.ContentTemplateContainer.Controls.Add(button1)
        up1.ContentTemplateContainer.Controls.Add(label1)
        Page.Form.Controls.Add(up1)

    End Sub
    Protected Sub Button_Click(ByVal Sender As Object, ByVal E As EventArgs)
        Dim lbl As Label
        lbl = Page.FindControl("Label1")
        lbl.Text = "Panel refreshed at " & _
            DateTime.Now.ToString()
    End Sub

</script>

<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
    <title>UpdatePanel Added Programmatically Example</title>
</head>
<body>
    <form id="form1" runat="server">
        <div>
            <asp:ScriptManager ID="TheScriptManager"
                               runat="server" />
        </div>
    </form>
</body>
</html>
<%@ Page Language="C#" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 
 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<script runat="server">

    protected void Page_Load(object sender, EventArgs e)
    {
        UpdatePanel up1 = new UpdatePanel();
        up1.ID = "UpdatePanel1";
        up1.UpdateMode = UpdatePanelUpdateMode.Conditional;
        Button button1 = new Button();
        button1.ID = "Button1";
        button1.Text = "Submit";
        button1.Click += new EventHandler(Button_Click);
        Label label1 = new Label();
        label1.ID = "Label1";
        label1.Text = "A full page postback occurred.";
        up1.ContentTemplateContainer.Controls.Add(button1);
        up1.ContentTemplateContainer.Controls.Add(label1);
        Page.Form.Controls.Add(up1);

    }
    protected void Button_Click(object sender, EventArgs e)
    {
        ((Label)Page.FindControl("Label1")).Text = "Panel refreshed at " +
            DateTime.Now.ToString();
    }

</script>

<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
    <title>UpdatePanel Added Programmatically Example</title>
</head>
<body>
    <form id="form1" runat="server">
        <div>
            <asp:ScriptManager ID="TheScriptManager"
                               runat="server" />
        </div>
    </form>
</body>
</html>

Controls that Are Not Compatible with UpdatePanel Controls

The following ASP.NET controls are not compatible with partial-page updates, and are therefore not designed to work inside an UpdatePanel control:

  • TreeView control under several conditions. One is when callbacks are enabled that are not part of an asynchronous postback. Another is when you set styles directly as control properties instead of implicitly styling the control by using a reference to CSS styles. Another is when the EnableClientScript property is false (the default is true). Another is if you change the value of the EnableClientScript property between asynchronous postbacks. For more information, see TreeView Web Server Control Overview.

  • Menu control when you set styles directly as control properties instead of implicitly styling the control by using a reference to CSS styles. For more information, see Menu Control Overview.

  • FileUpload and HtmlInputFile controls when they are used to upload files as part of an asynchronous postback.

  • GridView and DetailsView controls when their EnableSortingAndPagingCallbacks property is set to true. The default is false.

  • Login, PasswordRecovery, ChangePassword, and CreateUserWizard controls whose contents have not been converted to editable templates.

  • The Substitution control.

To use a FileUpload or HtmlInputFile control inside an UpdatePanel control, set the postback control that submits the file to be a PostBackTrigger control for the panel. The FileUpload and HtmlInputFile control can be used only in postback scenarios.

All other controls work inside UpdatePanel controls. However, in some circumstances, a control might not work as expected inside an UpdatePanel control. These circumstances include the following:

  • Registering script by calling registration methods of the ClientScriptManager control.

  • Rendering script or markup directly during control rendering, such as by calling the Write method.

If the control calls script registration methods of the ClientScriptManager control, you might be able to use corresponding script registration methods of the ScriptManager control instead. In that case, the control can work inside an UpdatePanel control.

Using Web Parts Controls Inside UpdatePanel Controls

ASP.NET Web Parts is an integrated set of controls for creating Web sites that enable end users to modify the content, appearance, and behavior of Web pages directly from a browser. You can use Web Parts controls inside UpdatePanel controls with the following restrictions:

  • Every WebPartZone control must be inside the same UpdatePanel control. For example, you cannot have two UpdatePanel controls on the page, each with its own WebPartZone control.

  • The WebPartManager control manages all client state information for Web Part controls. It must be in the outermost UpdatePanel control on a page.

  • You cannot import or export Web Parts controls by using an asynchronous postback. (Performing this task requires a FileUpload control, which cannot be used with asynchronous postbacks.) By default, importing Web Parts controls performs a full postback.

  • You cannot add or modify the styles of Web Parts controls during asynchronous postbacks.

For more information about Web Parts controls, see ASP.NET Web Parts Overview.

Properties and Methods not Supported During Asynchronous Postbacks

The following scenarios for setting the default postback button on a page are not supported during asynchronous postbacks:

  • Changing the DefaultButton programmatically during an asynchronous post back.

  • Changing the DefaultButton programmatically during an asynchronous post back when the Panel control is not inside of an UpdatePanel control.

The following methods of the HttpResponse class are supported only in postback scenarios and not in asynchronous postback scenarios:

Code Examples

The following sections include examples that show how to create and use UpdatePanel controls.

How-to and Walkthrough Topics

Class Reference

The key server classes for UpdatePanel controls are shown in the following table.

Class

Description

UpdatePanel

A server control that specifies the parts of a Web page that can participate in partial-page updates.

ScriptManager

A server control that manages partial-page rendering. The ScriptManager control registers script components to send to the browser. It also overrides page rendering so that only specified regions of the page are rendered.

ScriptManagerProxy

A server control that enables nested components (such as content pages or user controls) to add script and Web-service references. This control is useful if the parent element already contains a ScriptManager control.

PageRequestManager

A class in the Microsoft AJAX Library that coordinates partial-page rendering in the browser. The PageRequestManager class asynchronously exchanges information with the server, and exposes events and methods for custom client script development.

Additional Topics

ASP.NET Page Life Cycle Overview

See Also

Tasks

Introduction to the UpdatePanel Control

Creating a Simple ASP.NET Page with Multiple UpdatePanel Controls

Concepts

UpdateProgress Control Overview

Partial-Page Rendering Overview

ASP.NET PageRequestManager Class Overview