I have a GridView in an aspx page where I'm comparing two dates and formatting them based on the result. Which seems to work fine except there are cases where I have a Null date or a blank cell which causes the page to crash and visual studio to return this error
An exception of type 'System.FormatException' occurred in mscorlib.dll but was not handled in user code. Additional information: String was not recognized as a valid DateTime.
This is where I get the error:
Dim startdate As DateTime = Convert.ToDateTime(e.Row.Cells(7).Text)
Here is my VB.Net code:
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
Dim duedate As DateTime = Convert.ToDateTime(e.Row.Cells(11).Text)
Dim startdate As DateTime = Convert.ToDateTime(e.Row.Cells(7).Text) '*THIS IS WHERE I HAVE NULL OR BLANK DATES
Dim today As DateTime = DateTime.Now
If startdate > duedate Then
e.Row.Cells(2).BackColor = System.Drawing.Color.Red
e.Row.Cells(2).CssClass = "gvhlrow"
ElseIf startdate.AddDays(7) < duedate Then
e.Row.Cells(2).BackColor = System.Drawing.Color.Yellow
e.Row.Cells(2).CssClass = "gvhlrow"
ElseIf startdate.AddDays(14) < duedate Then
e.Row.Cells(2).BackColor = System.Drawing.Color.Lime
e.Row.Cells(2).CssClass = "gvhlrow"
ElseIf startdate < duedate Then
e.Row.Cells(2).BackColor = System.Drawing.Color.Orange
e.Row.Cells(2).CssClass = "gvhlrow"
End If
End If
End Sub
You have to check your inputs using something like this:
Dim startdate As DateTime
If Not DateTime.TryParse(e.Row.Cells(7).Text, startdate) Then
' Display an error, set a meaningful default value or just return.
End If
Maybe you want to display an error message to the user in case of an invalid date, maybe you want to ignore it and use some default value or if there isn't a meaningful default value then you just might want to return without any calculation.
I would recommend to check duedate
for invalid values in a similar manner.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.