Friday, November 13, 2009

ASP.NET 2.0 AJAX Extensions Update Panel - Multiple Update Panels

One of the main properties of an UpdatePanel is its UpdateMode property. The UpdateMode property is by default set to "Always".
However, when you have more than a single update panel or when you want to control as to when the Update Panel needs to get refresh, then setting the UpdateMode property to "Condition" is the first step.
Let us consider a scenario where we have 3 Update Panels in a page. The HTML for the same is as below:-
<form id="form1" runat="server">
<asp:ScriptManager ID="ScriptManager1" runat="server">
</asp:ScriptManager>
<div>
<table width="100%">
<tr>
<td style="height: 64px">
<asp:UpdatePanel ID="UpdatePanel1" runat="server" UpdateMode="Conditional">
<ContentTemplate>
<b><u>Section 1</u></b>
<br /><br />
<asp:Label ID="Label1" runat="server"></asp:Label>
<asp:TextBox ID="TextBox1" runat="server" />
<br /><br />
<asp:Button ID="Button1" runat="Server" Text="Refresh" OnClick="Button1_Click" />
</ContentTemplate>
</asp:UpdatePanel>
</td>
<td style="height: 64px">
<asp:UpdatePanel ID="UpdatePanel2" runat="server" UpdateMode="Conditional">
<ContentTemplate>
<b><u>Section 2</u></b>
<br /><br />
<asp:Label ID="Label2" runat="server"></asp:Label>
<asp:TextBox ID="TextBox2" runat="server" />
<br /><br />
<asp:Button ID="Button2" runat="Server" Text="Refresh" OnClick="Button2_Click" />
</ContentTemplate>
</asp:UpdatePanel>
</td>
<td style="height: 64px">
<asp:UpdatePanel ID="UpdatePanel3" runat="server" UpdateMode="Conditional">
<ContentTemplate>
<b><u>Section 3</u></b>
<br /><br />
<asp:Label ID="Label3" runat="server"></asp:Label>
<asp:TextBox ID="TextBox3" runat="server" />
<br /><br />
<asp:Button ID="Button3" runat="Server" Text="Refresh" OnClick="Button3_Click" />
</ContentTemplate>
</asp:UpdatePanel>
</td>
</tr>
</table>
</div>
</form>

Note that for all the UpdatePanels, I have set the UpdateMode to conditional. The application logic or codebehind for the above is as follows:-
protected void Page_Load(object sender, EventArgs e){
Label1.Text = System.DateTime.Now.ToString();
Label2.Text = System.DateTime.Now.ToString();
Label3.Text = System.DateTime.Now.ToString(); }
protected void Button1_Click(object sender, EventArgs e) { TextBox2.Text = TextBox1.Text; }
protected void Button2_Click(object sender, EventArgs e){ }
protected void Button3_Click(object sender, EventArgs e){ }
When you run this page, you will notice that there are four Sections - Section 1, 2 & 3. When you click on the Refresh button, the date time value gets refreshed only for the particular section. The other values doesnt get changed.
If you remove the UpdateMode=Conditional from the above UpdatePanel declarations, you will notice that all the labels get refreshed.
Hence, setting the UpdateMode as Conditional is important if you like to control the way the UpdatePanels get refreshed.

No comments: