Share via

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!

Developer technologies | VB
Developer technologies | ASP.NET Core | Other
0 comments No comments

Answer accepted by question author

Albert Kallal 5,591 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

Was this answer helpful?


0 additional answers

Sort by: Most helpful

Your answer

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