Difference in 2 dates

I am changing the row color of my gridview based on how many days have passed since this task. But that does not work date1 - today's date and date2 is the deadline for the task.

also, when I sort, I click on the column headings 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.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



    Next
End Sub

enter image description here

+3
source share
3 answers

Took the time, but in the end I noticed it.

You scroll through each line and then only update the one that is in the database!

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

Your code should be as follows:

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
+2
source

You may need TotalDaysout TimeSpan.

0
source

date1 = Date.Now

date1 = Date.Now.Date

Date.Now . , , .

0

Source: https://habr.com/ru/post/1790498/


All Articles