Count days out of gridview row databound in one cell

Phillip Vong 121 Reputation points
2021-07-05T16:21:35.097+00:00

First - Thanks for helping a newbie. Doing this in VB.net / asp.net.

Goal - During a GridView RowDataBound, I want to...

Check each row and see if Column 5 is Blank
If not blank
convert to date and see if that date is less than 365 of today
If less than 365, make that cell backcolor yellow

Col(5) data type in SQL is DATE
Col(5) DataFormatString in Gridview is {0:d}

My Code:

 Private Sub GridView1_RowDataBound(sender As Object, e As GridViewRowEventArgs) Handles GridView1.RowDataBound

        If Not e.Row.Cells(5).ToString = String.Empty Then

            Dim CoDateToDate As Date = Convert.ToDateTime(e.Row.Cells(5))
            Dim Ct As Int32 = DateDiff(DateInterval.Day, CoDateToDate.Day, Now.Day)

            If Ct < 365 Then
                e.Row.Cells(5).BackColor = Drawing.Color.Yellow
            End If
        End If


    End Sub

My Error Message
'Unable to cast object of type 'System.Web.UI.WebControls.DataControlFieldHeaderCell' to type 'System.IConvertible'.'

My Imports - don't know if I'm not importing the right things.
Imports System.Data, System.Data.SqlClient, System.Web.UI.WebControls

I didn't see a way to CONVERT to Date. I can only Convert to DateTime. Is this the problem with the SQL datatype is just DATE?

Please help and thanks!

ASP.NET
ASP.NET
A set of technologies in the .NET Framework for building web applications and XML web services.
3,542 questions
VB
VB
An object-oriented programming language developed by Microsoft that is implemented on the .NET Framework. Previously known as Visual Basic .NET.
2,756 questions
0 comments No comments
{count} votes

Accepted answer
  1. Albert Kallal 5,331 Reputation points
    2021-07-05T19:56:21.873+00:00

    What you have looks ok - but when the data bound triggers, it ALSO will include the heading and the footing grid row - you ONLY want to process/run your code for a data row.

    so, wrap your existing code in this:

        If e.Row.RowType = DataControlRowType.DataRow Then
    
        End If
    

    Regards,
    Albert D. Kallal (Access MVP 2003-2017)
    Edmonton, Alberta Canada


0 additional answers

Sort by: Most helpful

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.