Search code examples
c#asp.netwebformsupdatepanel

Update an update panel within loop ASP.Net Web Forms C#


I have been trying to find a way to relay incremental feedback of a process to the UI via an update panel. A basic example of what I am trying to implement is as follows:

protected void DoSomething(object sender, EventArgs e) {
    for(int i=0; i < 10; i++){
       //Pretend to do something intensive
       Thread.Sleep(1000);
       //Output the progress of the process to a label
       Label.Text = i.ToString();
     }
 }

The aspx markup in my example is simply:

<asp:UpdatePanel ID="UpdatePanel1" runat="server" UpdateMode="Conditional">
<ContentTemplate>
<asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>
</ContentTemplate>
<Triggers>
    <asp:AsyncPostBackTrigger ControlID="Button1" />
</Triggers>

<asp:Button ID="Button1" runat="server" OnClick="DoSomething" Text="Push Me"/>

However when Button1 is pressed the UpdatePanel does not update incrementally, instead it only displays the number 9 when the loop completes.

I believe this is because no postback is triggered until the server side code completes (i.e. when the loop stops looping).

Is there a way I can achieve the desired functionality using server side code and update panels?

Thanks in advance! :)


Solution

  • What you can do is, create a timer object in design mode (or punch it in your html code) and also add a async trigger to that timer. This link will help you a great deal!

    http://msdn.microsoft.com/en-us/library/vstudio/bb386404(v=vs.100).aspx

    In other words, the timer will trigger update in panel in that time interval you set up :) In code behind, every timed event,y ou update your update panel w/ incremental value.