开发者

difference of 2 dates coming out wrong

I am changing the row color of my gridview based on how many days the task is from today. But it is not working date1 is todays date and date2 is the due date of the task.

also when i sort i click on the column headers to sort, the rows change colors

Protected Sub GridView6_RowDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewRowEventArgs)
    Dim date1 As Date
    date1 = Date.Now

    Dim date2 As Date

    For Each row As GridViewRow In GridView6.Rows
        Dim ddate As Label = CType(row.FindControl("label1"), Label)
        date2 = Date.Parse(ddate.Text)

        Dim ts As TimeSpan = date2.Subtract(date1)
        Dim days As Integer = ts.TotalDays



        If days <= 14 Then
            e.Ro开发者_StackOverfloww.ForeColor = System.Drawing.Color.Red
        ElseIf days > 14 And ts.Days < 30 Then
            e.Row.ForeColor = System.Drawing.Color.Blue
        ElseIf days >= 30 Then
            e.Row.ForeColor = System.Drawing.Color.LightGreen
        End If



    Next
End Sub

difference of 2 dates coming out wrong


Took a while, but eventually I spotted it.

You are looping through every row, then only updating the one being databound!

Get rid of your foreach row in grid.Rows, and just work on the row in e.Row.

Your code should be this:

Protected Sub GridView6_RowDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewRowEventArgs)     
  Dim date1 As Date     
  date1 = Date.Now      
  Dim date2 As Date      

  Dim ddate As Label = CType(e.Row.FindControl("label1"), Label)         
  date2 = Date.Parse(ddate.Text)          
  Dim ts As TimeSpan = date2.Subtract(date1)         
  Dim days As Integer = ts.TotalDays            
  If days <= 14 Then             
    e.Row.ForeColor = System.Drawing.Color.Red         
  ElseIf days > 14 And ts.Days < 30 Then 
    e.Row.ForeColor = System.Drawing.Color.Blue         
  ElseIf days >= 30 Then 
    e.Row.ForeColor = System.Drawing.Color.LightGreen         
End If         
End Sub


You might want TotalDays from the TimeSpan.


Replace

date1 = Date.Now

with

date1 = Date.Now.Date

Date.Now contains the time part also. It seems from the context that, you are interested only of date difference ,not considering the time.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜