Calculated value of a field in the row is getting displayed in the next row instead of the same one

I have a Gridview in which I am pulling data from an access database. One of the columns in the gridview pulls a field named Last Login Date. I want to calculate the difference between the Last Login Date and the Current Date and display the calculated difference in an additional column in the same row. I have verified that the calculation is happening just fine. But when the page is displayed, the calculated value is getting displayed in the next row instead of the same row. The value of Difference in the first row is showing as 0 (zero).

Calculated Values
Idle Since Current Date and Time Last_Log_Date
Showing 0 instead of 9. 9 is getting displayed in next row.--------------------------------------- 0 7/26/2008 11:23 7/17/2008 22:46
This value is actually the calculated value using the data fields in previous row----- 9 7/26/2008 11:23 7/17/2008 22:54
same as above  9 7/26/2008 11:23 7/25/2008 2:32
' 1 7/26/2008 11:23 7/23/2008 9:49
' 3 7/26/2008 11:23 7/23/2008 5:23
' 3 7/26/2008 11:23 7/23/2008 5:24
' 3 7/26/2008 11:23 7/17/2008 18:35

 

Here's the code behind my ASPX Page:

Imports System.ComponentModel

Partial Class _Default

Inherits System.Web.UI.Page

Public idleage As Integer

Protected Sub GridView1_RowDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles GridView1.RowDataBound

If (e.Row.RowType = DataControlRowType.DataRow) Then

'Add Decoration in the Gridview when a row is clicked

e.Row.Attributes.Add("onmouseover", "this.style.cursor='hand';this.style.textDecoration='underline';")

e.Row.Attributes.Add("onmouseout", "this.style.textDecoration='none';")

e.Row.Attributes.Add("onclick", "this.style.cursor='hand';this.style.forecolor='blue';")

 

e.Row.Attributes.Add(
"onclick", ClientScript.GetPostBackClientHyperlink(Me.GridView1, "Select$" + e.Row.RowIndex.ToString()))

 

'Calculate difference between Last Login Date and Current Date

Dim lastlog As String = e.Row.Cells(2).Text

Dim dt As Date = DirectCast((TypeDescriptor.GetConverter(New Date(2008, 7, 1)).ConvertFrom(lastlog)), Date)

Dim diff As TimeSpan = Date.Now.Subtract(dt)

idleage = diff.TotalDays

End If

End Sub

End Class

The code on the aspx page is below.

<html xmlns="http://www.w3.org/1999/xhtml">

<head runat="server">

<title>Untitled Page</title>

</head>

<body>

<form id="form1" runat="server">

<asp:GridView ID="GridView1" runat="server" CellPadding="4"

DataSourceID="SqlDataSource1" ForeColor="#333333" GridLines="None">

<FooterStyle BackColor="#990000" Font-Bold="True" ForeColor="White" />

<RowStyle BackColor="#FFFBD6" ForeColor="#333333" />

<Columns>

<asp:templatefield headertext="Idle Since"

itemstyle-horizontalalign="Right"

footerstyle-horizontalalign="Right"

footerstyle-backcolor="Blue"

footerstyle-forecolor="White">

<itemtemplate>

<asp:label id="Idle"

runat="server" Text='<%#idleage%>'/>

</itemtemplate>

</asp:templatefield>

<asp:templatefield headertext="Current Date and Time"

itemstyle-horizontalalign="Right"

footerstyle-horizontalalign="Right"

footerstyle-backcolor="Blue"

footerstyle-forecolor="White">

<itemtemplate>

<asp:label id="Today"

runat="server" Text='<%#DateTime.Now%>'/>

</itemtemplate>

</asp:templatefield>

</Columns>

<PagerStyle BackColor="#FFCC66" ForeColor="#333333" HorizontalAlign="Center" />

<SelectedRowStyle BackColor="#FFCC66" Font-Bold="True" ForeColor="Navy" />

<HeaderStyle BackColor="#990000" Font-Bold="True" ForeColor="White" />

<AlternatingRowStyle BackColor="White" />

</asp:GridView>

<asp:SqlDataSource ID="SqlDataSource1" runat="server"

ConnectionString="<%$ ConnectionStrings:New_TestConnectionString %>"

ProviderName="<%$ ConnectionStrings:New_TestConnectionString.ProviderName %>"

SelectCommand="SELECT [Last Log Date] AS Last_Log_Date FROM [Linked_Save]">

</asp:SqlDataSource>

</form>

</body>

</html>

how can i correct this problem. Appreciate the help.

 

Thanks,

Prateek

0
lost_floyd
7/26/2008 6:29:14 AM
asp.net.presentation-controls 72751 articles. 3 followers. Follow

2 Replies
1063 Views

Similar Articles

[PageSpeed] 25

 Hi lost_floyd,

I have done a few modifications on your aspx and aspx.cs page
Coding is on C#
Simple enough to convert

In ASPX

<asp:GridView ID="GridView1" runat="server" CellPadding="4" DataSourceID="SqlDataSource1" AutoGenerateColumns="false"
    ForeColor="#333333" GridLines="None"
    onrowdatabound="GridView1_RowDataBound">
    <FooterStyle BackColor="#990000" Font-Bold="True" ForeColor="White" />
    <RowStyle BackColor="#FFFBD6" ForeColor="#333333" />
    <Columns>
        <asp:TemplateField HeaderText="Idle Since" ItemStyle-HorizontalAlign="Right" FooterStyle-HorizontalAlign="Right"
            FooterStyle-BackColor="Blue" FooterStyle-ForeColor="White">
            <ItemTemplate>
                <asp:Label ID="lblIdle" runat="server" Text='<%#idleage%>' />
            </ItemTemplate>
        </asp:TemplateField>
        
        <asp:TemplateField HeaderText="Current Date and Time" ItemStyle-HorizontalAlign="Right"
            FooterStyle-HorizontalAlign="Right" FooterStyle-BackColor="Blue" FooterStyle-ForeColor="White">
            <ItemTemplate>
                <asp:Label ID="lblToday" runat="server" Text='<%#DateTime.Now%>' />
            </ItemTemplate>
        </asp:TemplateField>
        
        <asp:TemplateField HeaderText="Last Login" ItemStyle-HorizontalAlign="Right" FooterStyle-HorizontalAlign="Right"
            FooterStyle-BackColor="Blue" FooterStyle-ForeColor="White">
            <ItemTemplate>
                <asp:Label ID="lblDBDate" runat="server" Text='<%#Eval("Last_Log_Date")%>' />
            </ItemTemplate>
        </asp:TemplateField>

        
    </Columns>
    <PagerStyle BackColor="#FFCC66" ForeColor="#333333" HorizontalAlign="Center" />
    <SelectedRowStyle BackColor="#FFCC66" Font-Bold="True" ForeColor="Navy" />
    <HeaderStyle BackColor="#990000" Font-Bold="True" ForeColor="White" />
    <AlternatingRowStyle BackColor="White" />
</asp:GridView>

In ASPX.CS

protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
    if (e.Row.RowType == DataControlRowType.DataRow)
    {
        Label lblDateNow = e.Row.FindControl("lblToday") as Label;
        Label lblDateDB = e.Row.FindControl("lblDBDate") as Label;
        Label lblIdleSince = e.Row.FindControl("lblIdle") as Label;

        DateTime dtToday = Convert.ToDateTime(lblDateNow.Text);
        DateTime dtDB = Convert.ToDateTime(lblDateDB.Text);
        TimeSpan tsDateDiff = dtToday - dtDB;

        lblIdleSince.Text = tsDateDiff.Days.ToString();

    }
}

This will do.


Regards,
Naveen

Please remember to click Mark as Answer on the post that helps you, and to click Unmark as Answer if a marked post does not actually answer your question.
View Blog
0
naveenj
7/26/2008 9:26:27 AM

Thanks a Ton Naveen... that solved my problem... you guys are wonderful !!

Cheers !

0
lost_floyd
7/26/2008 12:49:36 PM
Reply:

Similar Artilces:

Code to automatically caculate a field value, is not displaying the calculated value in the footer row
Hello, I am using the code below to automatically caculate TotalHoursPerUnit after I click the edit button and enter a number in the HeoursPerUnit & PeoplePerUnit fields.  I added a footer row to the Gridview and updated GridView1_RowDataBound to automatically caculate the TotalHoursPerUnit footer row textbox NewTotalHoursPerUnit in the footer row, but no luck.  I do not get an errors.  Any suggestions? aspx page <%@ Page Language="VB" MasterPageFile="~/MembersDefault.master" AutoEventWireup="false" CodeFile="frmHR.as...

Reduce rows displayed but putting 3 rows in one row
Hi all, I'm using PB6.5. I have an SQL DW that fetch some information from the DB but should display only two columns: a code and a value. Also they are displayed in the trailer of a group if that's actually important. In order to reduce displayed rows count, i would like to display each 3 rows in one row(Code,Value,Code,Value,Code,Value). The question is how can i do that?. I've tried to use computed fields and in the second and third pair values to use code[1],value[1],code[2],value[2] but only the code[1],value[1] are OK(Showing next row's data), the third ...

First Row, Next Row, Prior Row, Last Row
I have a SQL Anywhere 7.0 Database, have a table Product_detail which contains Column Name Datatype width Null Default batch_id char(10) No None prod_id Integer No None employee_id Integer No None quantity Integer No None price Numeric (14, 2) No None Its primary key is batch_id I have a Freeform Datawindow with this table I want to provide the first row, next row, prior row and last row Ho...

select the row of the datagrid whose value is same as one of the value of row of datagrid
hellow all,  I have a datagrid which is bound to the ordertable,so all the orderdetails are shown on the page load. but my requirement is that,i have a textbox and a search button,when the user enter the order number in the text box and click on the search button the datagrid should show that record whose order number is entered by the user n most imp that the record may be in the 65th or 34th row of the datagrid,i wants to put it in the first row. how to do it. If there's a reason you can't filter down to just the one row, you'll have to come up with some paging algorithm that wil...

How do i get one row if the resultset returned has no rows.
Hi I have couple of CTE's which i want to ultimately insert into a temp table... and based on my condition some of the CTE's return some rows and some dont... but i want to have the CTE return atleast one row if there is no data in it.. I have tried doing the following but i am not getting the desired output    ;with cte_rpt4 as (select '4' a,recd_dt as approve_dt, prov_no, prov_name, client_id, claim_mst_id, claim_adj_id, claim_dt, claim_amt, rpt4, (Select count(distinct(Claim_mst_Id)) as crpt4 from #temp1 where datediff(day,isnull(recd_dt,create_dt),isnull(c...

Get next row values
Hello, I would like to get the values present in the next row depending on which row is currently being edited.  How would I begin doing that? When you are in the process of editing, you'll have the current EditIndex. With this, you can retrieve the row for that index plus one. Once you have a reference to the row, you can extract the values from it.Thanks, EdMicrosoft MVP - ASP/ASP.NET...

DetailView (Header in one Row and Item or Value in other Row)
My second question is, how can I put header in one row and ItemValue in other row. Currently the detail view is showing data as following structure: FieldName:         FieldValueFieldName:         FieldValueFieldName:         Listitem1                           Listitem2            &nbs...

Display data in one row with many child rows
Hi all, Could i display data like this :                             DetailPerson        Column 1       Column 2                   name 1         address 1person 1      age 1         &nbs...

Displaying 2 rows as one row in GridView--very urgent
Hi I need to display 2 rows as a one row in Gridview like this in text boxes and also I need horizontal paging on the gridview... any help would be much appreciated !!! ---------------------------------------------------------<<  Jan| Feb| Mar| Apr| May| Jun| Jul|   >>---------------------------------------------------------  A  10 |  20 |  30 |  40 |  50 |  60 |  70 |  B  10 |  20 |  30 |  40 |  50 |  60 |  70 |&...

How to get the row index of a selected row in listview control
Can someone please tell me how to get the index of a selected row in a listview.  <ItemTemplate> <asp:LinkButton runat="server" class="linkButton" id="xxxxx" Text='<%#Eval("documenttype") %>' CommandName="OpenFile" CommandArgument='<%#Eval("DocumentKey") %>'></asp:LinkButton></ItemTemplate>what you have to do is, in itemcommand event of ListView, you have to get the value of row indexif(e.CommandName == "corrospondingcommaandname"){     &nb...

Compare the last in one row with the first in the next row
--____QVLZYPRMMGJPQCYPSFRH____ Content-Type: text/plain; charset=iso-8859-1 Content-Transfer-Encoding: quoted-printable In our timecard datawindow, I want to highlight where there are 'gaps'. 1/1/08 08:00 1/1/08 11:00 1/1/08 12:00 1/1/08 05:00 I want the 12:00 to be highlighted because it isn't the same as the second = datetime in the previous row. Can someone help me with some script for this? --____QVLZYPRMMGJPQCYPSFRH____ Content-Type: multipart/related; boundary="____RNQEGPGXMIMQCYOCQRWY____" --____RNQEGPGXMIMQCYOCQRWY____ Content-Type: tex...

ADO.net problem: i can not view image data for the rest of my table rows except the image for the first row but i can read all the other non image fields for all rows.
Hi i have a table with the following fields imgid............int imgdata........image imgtitle.........varchar(max) imgType........varchar(max) imgLength.....bigint incident_id.....int i have no problem with uploading the image but viewing the uploaded image(s) in a gridview has caused me great pain. The probelm is i have two pages. page1 grabs the image to display and page2 has a gridview that displays the grabed image. I wanted to have an sql statement like SELECT * FROM mytable WHERE incident_id=someValue. IF i have 5 records in this table and i view page2 ...

Add new controls to a gridview row; when editing that row using the edit row feature in the gridview control.
Hi all  I have a questions that looks hard / complex to me, and i know you can help me in this. Q {  I have row in a Gridview and i have an edit option to it. I press the edit button, to edit the values in that row and update data all the way back to the database. Now when i press the edit button, i want a drop down list to be displayed that contain values for a particular field in my grid view. (for now only plain text boxes appear.) } I hope you understand my question, all i need to do is replace the text box controls with a dropdown list when i am editing a row in ...

Get the value of any rows into a DetailsView control:
Hi all, I would like to catch the value of a row for a specific row of a detailsview control. I am using a command field which is raised with the OnItemCommand="ChangeRole_Click" property of my DetailsView. I am trying to reach the content of this detailsview by doing somthing like this: void ChangeRole_Click(object sender, DetailsViewCommandEventArgs e) { string recupRole = ((DetailsView)sender).Rows[0].ToString(); Response.Write(recupRole); } But it doesn't work :( Someone could help ? Thanks in advance Benjamin I ha...

Web resources about - Calculated value of a field in the row is getting displayed in the next row instead of the same one - asp.net.presentation-controls

Calculated Risk - Wikipedia, the free encyclopedia
^ Streitfeld, David (December 1, 2008). "Doris Dungey, Prescient Finance Blogger, Dies at 47" . New York Times. p. A27, New York edition . h ...

Image from page 12 of "The American anti-slavery almanac, for ... : calculated for Boston, New York ...
Identifier: americanantislav1838chil Title: The American anti-slavery almanac, for ... : calculated for Boston, New York, and Pittsburgh .. Year: ...

Cosy deal calculated to aid fund managers
A few years back, the corporate regulators did the fund managers a big favour.

Paris shooting: Charlie Hebdo gunmen were not crazy, just calculated
Sometimes crazy men are not crazy; not in any clinical sense. Some crazy men do what they do because they make a cold and reasoned decision that ...

Joe Hockey's change of heart on uni fees is calculated
Thank you, Waleed Aly, for your eye-opening article ("Gotcha politics is just light entertainment", May 30). It would be hypocritical not to ...

Taylor Swift is terribly calculated and mean, says Grizzly Bear's Edward Droste
The lead singer from Brooklyn indie band Grizzly Bear has taken down Taylor Swift on Twitter and admitted to being genuinely scared of the successful ...

Canterbury Bulldogs' calculated leap of faith in Michael Lichaa places weight of expectation on his shoulders ...
Even the expectation of bursting into the NRL as the hottest rookie in the game could not have prepared Michael Lichaa for what would unfold ...

Keystone XL Emissions Could Be Four Times Higher Than U.S. Calculated, Says New Study
WASHINGTON - The much-debated Keystone XL pipeline could produce four times more global warming pollution than the State Department calculated ...

Size matters, but so does how it is calculated
Size matters, but so does how it is calculated

Stop Giving Away the Store: “Reasonably Calculated” does not define the scope of discovery. (And it never ...
For over a hundred years Americans have enjoyed Josh Billing’s chestnut, “I’d rather not know so much, than to know so much that ain’t so.” ...

Resources last updated: 12/15/2015 2:54:47 AM