0

Iam newbie to ASP.NET, and this is my first question on this forum. Here is my code:

protected void Button1_Click(object sender, EventArgs e)
        {
            for (int i = 0; i < 10; i++) 
            {
                Label2.Text = i.ToString();
                UpdatePanel1.Update();
                Thread.Sleep(3000);
            }
        }


<asp:UpdatePanel ID="UpdatePanel1" runat="server">
        <ContentTemplate>
            <asp:Label ID="Label1" runat="server" Text=""></asp:Label>
            <asp:Button ID="Button1" runat="server" Text="Button" onclick="Button1_Click"/>
            <asp:Label ID="Label2" runat="server" Text=""></asp:Label>
        </ContentTemplate>
</asp:UpdatePanel>

I want to display the value of i each time when its get updated, but I got the value 9. Please help me how can achieve my goal... No luck so far

2
  • I suggest putting a breakpoint at Thread.Sleep(3000); and then actually checking the label to make sure it's being updated properly. Commented Oct 25, 2013 at 19:49
  • @kehrk: The label control on the server side will be updated just fine, but nothing is sent to the browser until the server code ends. Commented Oct 25, 2013 at 19:55

1 Answer 1

3

You can't update the page in the browser directly from server code. Any updates to the page are sent back to the page when the server code ends.

The Update method only tells the update panel that it should be included in the data that is sent back to the browser when the page is complete, it doesn't send the update directly to the browser.

To periodically update content in the browser using server code you have to control it from the browser, and the server code should just do one update and then exit so that the update is sent back to the browser. You can user a timer control that will make requests to the server for every tick, or you could use Javascript code to request data from a server page.

Sign up to request clarification or add additional context in comments.

1 Comment

@AtifRehmat: That would be hard, as I don't know where you are going with this. What you have now would be easier to solve with just client script without calling the server at all. You can start with trying out a timer control, that would be most consistent with what you have built so far. Just make it update something at an interval, for example putting DateTime.Now.ToString() in a label, then you can figure out how you want to keep track of values from one server call to the next.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.