简体   繁体   中英

ASP.net Javascript Countdown clock timer for each row of a gridview

Using Asp.net 4.0/C# SQL 2008

I have a page with a gridview on it. I need a countdown clock in the format HH:MM:SS that will count backwards until it reach the expiration date. My code is properly showing the clock for the first row of the gridview but any additional rows are not executing the javascript clock.

For testing purposes, I have a basic stored procedure that includes a generic primary key, Expiration date and the Current date. I call a javascript function that will then get the difference between the 2 dates and format them. Appreciate any assistance to help me get the countdown clock timer to appear on each row of the gridview.

Current SQL Code:

create proc dbo.tmpdate2 as
begin
select 1 as ElementID, DATEADD(HH,1,GETDATE()) AS ExpDate, getdate() as NowDate
union all
select 2 as ElementID, DATEADD(HH,2,GETDATE()) AS ExpDate, getdate() as NowDate
END    

Current ASPX Gridview Code:

     <asp:GridView ID="GridView1" runat="server" BackColor="White" 
    BorderColor="#DEDFDE" BorderStyle="None" BorderWidth="1px" CellPadding="4" 
    ForeColor="Black" GridLines="Vertical">
    <AlternatingRowStyle BackColor="White" />
    <Columns>
        <asp:TemplateField HeaderText="Todays Date">
            <ItemTemplate>
                <asp:Label ID="Label1" runat="server"><%# Eval("NowDate")%></asp:Label>
            </ItemTemplate>
        </asp:TemplateField>

        <asp:TemplateField HeaderText="Expiration Date">
            <ItemTemplate>
                <div>
                <label id="ElementID"><label>
                <script language="javascript" type="text/javascript">
                    function Countdown(ElementID, ExpDateTimeString, NowDateTimeString) {
                        var NowDateTime = new Date(NowDateTimeString);
                        var ExpDateTime = new Date(ExpDateTimeString);

                        // convert the current date and the target date into miliseconds                       
                        var NowDateTimeMS = (NowDateTime).getTime();
                        var ExpDateTimeMS = (ExpDateTime).getTime();

                        // find their difference, and convert that into seconds                 
                        var TimeLeftSecs = Math.round((ExpDateTimeMS - NowDateTimeMS) / 1000);

                        if (TimeLeftSecs < 0) {
                            TimeLeftSecs = 0;
                        }

                        var Hours = Math.floor(TimeLeftSecs / (60 * 60));
                        TimeLeftSecs %= (60 * 60);
                        var Minutes = Math.floor(TimeLeftSecs / 60);
                        if (Minutes < 10) {
                            Minutes = "0" + Minutes;
                        }
                        TimeLeftSecs %= 60;
                        var Seconds = TimeLeftSecs;
                        if (Seconds < 10) {
                            Seconds = "0" + Seconds;
                        }

                        document.getElementById('ElementID').innerHTML = Hours + ":" + Minutes + ":" + Seconds;

                        // increment the NowDateTime 1 second
                        NowDateTimeMS += 1000;
                        NowDateTime.setTime(NowDateTimeMS);
                        // recursive call, keeps the clock ticking
                        var FunctionCall = "Countdown('" + ElementID + "','" + ExpDateTime + "','" + NowDateTime + "');";
                        setTimeout(FunctionCall, 1000);
                    }
                </script>
                <script language="javascript" type="text/javascript">

                        var NowDateTime = new Date('<%# Eval("NowDate") %>');
                        var ExpDateTime = new Date('<%# Eval("ExpDate") %>');
                        var ElementID = "00:00:00"; 

                        // recursive call, keeps the clock ticking
                        var FunctionCall = "Countdown('" + ElementID + "','" + ExpDateTime + "','" + NowDateTime + "');";
                        setTimeout(FunctionCall, 1000);
                </script>
                </div>
            </ItemTemplate>
        </asp:TemplateField>


    </Columns>
    <FooterStyle BackColor="#CCCC99" />
    <HeaderStyle BackColor="#6B696B" Font-Bold="True" ForeColor="White" />
    <PagerStyle BackColor="#F7F7DE" ForeColor="Black" HorizontalAlign="Right" />
    <RowStyle BackColor="#F7F7DE" />
    <SelectedRowStyle BackColor="#CE5D5A" Font-Bold="True" ForeColor="White" />
    <SortedAscendingCellStyle BackColor="#FBFBF2" />
    <SortedAscendingHeaderStyle BackColor="#848384" />
    <SortedDescendingCellStyle BackColor="#EAEAD3" />
    <SortedDescendingHeaderStyle BackColor="#575357" />
</asp:GridView>

Current ASPX.CS Code:

protected void Page_Load(object sender, EventArgs e)
    {
        SqlConnection thisConnection = new SqlConnection(ConfigurationManager.ConnectionStrings["SomeConnectionString2"].ConnectionString);

        SqlCommand command = new SqlCommand("tmpdate2", thisConnection);
        command.CommandType = CommandType.StoredProcedure;

        SqlDataAdapter adapter = new SqlDataAdapter(command);

        DataTable table = new DataTable();

        adapter.Fill(table);

        GridView1.DataSource = table;
        GridView1.DataBind();
    }

The idea is to have a generic method and on each row, you call that method... for example:

your table column should only be:

    <ItemTemplate>
        <span id="timer_<%# Container.DataItemIndex %>" 
              class="timer" 
              data-start="<%# Eval("EndDate")%>"></span>
    </ItemTemplate>
</asp:TemplateField>

then, in your <script> block at the end of the page, you should have the timer countdown and fire it for each .timer element, like:

using jQuery to simplify

<script>
$(function() {
    $(".timer").each(function() {
        var startTime = $(this).data("start");
        Countdown($(this).attr("id"), startTime, new date());
    });
});

function Countdown(ElementID, ExpDateTimeString, NowDateTimeString) { 
    // your countdown...
}
</script>

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