简体   繁体   中英

C# How to raise PostBack on Timer.Tick event?

I use UpdatePanel with DataList element inside. I want to update the contents from DB every 10 secunds. I noticed that updating occures only after the postback. I did the code like

    <asp:UpdatePanel ID="UpdatePanel1" UpdateMode="Conditional" runat="server">
        <Triggers>
            <asp:AsyncPostBackTrigger ControlID="Timer1" EventName="Tick" />
        </Triggers>
        <ContentTemplate>
                <asp:DataList ID="lstComputers" runat="server" DataKeyField="ComputerID" DataSourceID="ComputersDataSource"
                    OnItemDataBound="lstComputers_ItemDataBound" OnItemCommand="lstComputers_ItemCommand">
                    <HeaderTemplate>

                    // Header data

                    </HeaderTemplate>
                    <ItemTemplate>

                    // Item template

                    </ItemTemplate>
                </asp:DataList>

                        <asp:UpdateProgress ID="UpdateProgress2" runat="server">
                            <ProgressTemplate>
                                <img border="0" src="images/loading.gif" />
                            </ProgressTemplate>
                        </asp:UpdateProgress>

        </ContentTemplate>
    </asp:UpdatePanel>

In code behind i tryed to use RaisePostBackEvent method but got Stack overflow exception...

    protected void Timer1_Tick(object sender, EventArgs e)
    {
        this.RaisePostBackEvent(Timer1, "");
    }

Remember that all your code-behind is executed on the server only. Therefore, if the Timer1_Tick() method is running, then your Timer is raising a PostBack.

The reason you get a StackOverflowException running that method is because it simply calls itself, infinitely. You need to place your update code in that method, not call it again recursively.

Take a look at the setTimeout() and setInterval() javascript functions. This all needs to happen on the client, not the server side.

protected void Timer1_Tick(object sender, EventArgs e)
{
    lstComputers.DataBind();
}

Solved the problem with data reloading

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM