Updating an UpdatePanel From Web User Control

Sometimes, there are cases when you need to do it. It's an easy task to understand and to perform too. 

You can download the code file attached here. 
 
The steps involved in the process are :
  • Place an UpdatePanel on the Page and set the UpdateMode property of the UpdatePanel as "Conditional".

<asp:UpdatePanel ID="UpdatePanelDemo" runat="server" UpdateMode="Conditional">
    <
ContentTemplate>
        <
div id="divDemo" runat="server" style="width: 400px; height: 200px; background-color: Gray;
        
border-radius: 10px; color: White; text-align: center; font-size: 30px; font-family: Calibri;
        
display: table-cell; vertical-align: middle;">
        Hi Folks
        </div>
    </
ContentTemplate>
</
asp:UpdatePanel>

Note: Don't forget to add an <asp:ScriptManager> tag.

  • Add a Button in Web User Control and add a OnClick handler.
<asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="Click To Update" />
  • Place the Web User Control on the page. Switch to the Design Mode (Shift + F7) -> Select Control from Solution Explorer -> Perform Drag & Drop (on page).

            Now switch to Source (F7); you will see that the control is registered on the page (just after the Page directive) and also placed.

<%@RegisterSrc="Controls/WebUserControl.ascx"TagName="WebUserControl"TagPrefix="uc1" %>

            I have placed it after the Update Panel, but it could be placed anywhere on the page (but inside the form).

<uc1:WebUserControl ID="WebUserControl1" runat="server" />

Run the WebSite; you will see the following output on the browser:

UpdatePanelDemo.gif

Now, come to the code behind of the Web User Control and write the following code in the "Button1_Click":

-----------------------------------------------------------------------------------------

//Finding UpdatePanel on Page
 UpdatePanel
updatePanelDemo = (UpdatePanel)this.Parent.FindControl("UpdatePanelDemo");
 //Finding divDemo on Page

 HtmlGenericControl divDemo = (HtmlGenericControl)this.Parent.FindControl("divDemo");
 //Setting InnerText property of divDemo
 
divDemo.InnerText = "I have Updated.......";
 //Updating UpdatePanel
 updatePanelDemo.Update();

-----------------------------------------------------------------------------------------

It's Done!!!


Go to the browser; refresh the page and click on the Button saying "Click To Update". You'll see this output:

Update Panel After Update


Similar Articles