Using of update panel (UpdatePanel) of ajax in asp.net

In  this tutorial i will explain how can we use UpdatPanel control which you can find in the section Ajax Extensions in the Toolbox...
UpdatPanel is used if you want to do partial post back i.e. if we want to post back only some part of the page & not whole page.
For example take a example of taking two numbers in the text box & showing it in the third text box on button click. As it is very easy you can create this of your own. create this all controls in the UpdatPanel.
Remember to put ScriptManager Control before the UpdatPanelas it is required to run any java script of Ajax.
Now take one more text box out side the UpdatPanel just to ensure that partial post back is occuring.
Your code will look something like this....


<div style="background-color:Gray;width:400px;padding:10px 0px 10px 10px;">
  <asp:ScriptManager ID="ScriptManager1" runat="server"></asp:ScriptManager>
    <asp:UpdatePanel ID="UpdatePanel1" runat="server">
      <ContentTemplate>
       First Number : <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
       <br />
       Second Number : <asp:TextBox ID="TextBox2" runat="server"></asp:TextBox>
       <br />
       <asp:Button ID="Button1" runat="server" Text="Add" onclick="Button1_Click" />
       <br />
       Addition :<asp:TextBox ID="TextBox3" runat="server"></asp:TextBox>
      </ContentTemplate>
    </asp:UpdatePanel>
</div>
<div style="margin-top:50px;background-color:Gray;width:400px;padding:10px 0px 10px 10px;">
  <asp:TextBox ID="TextBox4" runat="server"></asp:TextBox>
</div>
 
 
& button click code would be something like this ... 
 
    protected void Button1_Click(object sender, EventArgs e)
    {
        int a = Convert.ToInt32(TextBox1.Text);
        int b = Convert.ToInt32(TextBox2.Text);
        TextBox3.Text = (a + b).ToString();
    }
 
 
Now run your application.....
When page opens ...write something in the textbox which is outside the update panel ....
 
& then put some numbers in the first & second text box & click on add .....
Post back will happen only for that portion & addition will come on the third textbox .... 
But you can see that text written in the last textbox is as it is as only controls inside had a post back & not whole page...
 
UpdatePanel has two properties UpdateMode &  ChildrenAsTriggers .
 
UpdateMode:
It has two values
1)Always: It indicates that content of the each control in side that UpdatePanel should be updated on each post back which originates from the page.
2)Conditional:  It indicates that control should be updated only on the post back of specific controls.

ChildrenAsTriggers:
 When this property is set to true then any updates triggered by the nested UpdatePanel will also trigger an update to the parent UpdatePanel.

0 comments:

Post a Comment