比较两个日期和条件格式

时间:2016-10-27 11:49:48

标签: asp.net vb.net

我在aspx页面中有一个GridView,我在比较两个日期并根据结果格式化它们。这似乎工作正常,除非有我的Null日期或空白单元格导致页面崩溃和visual studio返回此错误

  

mscorlib.dll中发生了'System.FormatException'类型的异常   但未在用户代码中处理。附加信息:字符串是   未被识别为有效的DateTime。

这是我收到错误的地方:

Dim startdate As DateTime = Convert.ToDateTime(e.Row.Cells(7).Text)

这是我的VB.Net代码:

    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

1 个答案:

答案 0 :(得分:0)

您必须使用以下内容检查输入:

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

也许您希望在日期无效的情况下向用户显示错误消息,可能您想忽略它并使用某个默认值,或者如果没有有意义的默认值,那么您可能只想返回任何计算。

我建议以类似的方式检查duedate无效值。

相关问题