检查字符串值如果VB.net中的有效日期

时间:2014-03-19 06:35:34

标签: vb.net date datetime date-format

我的问题是当我收到一个字符串而且不是日期格式。并将错误放在文本框中。

示例:

Public Sub get_error(ByVal sheet_name As String, ByVal column_name As String, ByVal row_count As String, ByVal row_value As String)
        Dim dt_row_service_provider_code As String = row_value
        If dt_row_service_provider_code Is Nothing Or dt_row_service_provider_code = "" Then
            dt_row_service_provider_code = "Empty Value"
        End If
        If dt_row_service_provider_code.Length > 50 Then
            dt_row_service_provider_code = "Characters is greater than 50"
        End If
        txtError.Text += "sheet: " & sheet_name & " | column: " & column_name & " | row: " & (row_count + 2) & " | row value is: '" & dt_row_service_provider_code & "'" & Environment.NewLine
    End Sub

     'dr(2).Tostring contains word "test"
     For Each dr As DataRow In dt.Rows
        Dim holiday_code As String = dr(0).ToString
        Dim holiday_desc As String = dr(1).ToString
        Dim holiday_date As String = dr(2).ToString
       If holiday_date Is Nothing Or holiday_date = "" Then
             get_error(dt.TableName, dt.Columns(2).ToString, dt_row.ToString, "Empty Value")
        End If

          If isDate(holiday_date) = False Then
            'show error message in textbox
             get_error(dt.TableName, dt.Columns(2).ToString, dt_row.ToString, "Value is not a valid Date")
           End If
      Next

这只是我的一个例子,因为我的程序正在将excel导入数据库,我只是采取了一些场景,如果用户不小心在excel中添加日期格式的单词。如何将错误放在文本框中? 。我不想只显示异常,但我想把错误放在文本框中

1 个答案:

答案 0 :(得分:0)

更新了我的答案。

Public Sub get_error(ByVal sheet_name As String, ByVal column_name As String, ByVal row_count As Integer, ByVal row_value As String)
   Dim dt_row_service_provider_code As String = row_value
   txtError.Text += "sheet: " & sheet_name & " | column: " & column_name & " | row: " & (row_count + 2) & " | row value is: '" & dt_row_service_provider_code & "'" & Environment.NewLine

End Sub

For Each dr As DataRow In dt.Rows
    Dim holiday_code As String = dr(0).ToString
    Dim holiday_desc As String = dr(1).ToString
    Dim holiday_date As String = dr(2).ToString
    Dim newDate As DateTime
    Try
        newDate = DateTime.Parse(holiday_date)
    Catch ex As Exception
        If holiday_date = "" Or holiday_date Is Nothing Then
            get_error(dt.TableName, dt.Columns(2).ToString, dt.Rows.IndexOf(dr), "Empty Value")
        Else
            get_error(dt.TableName, dt.Columns(2).ToString, dt.Rows.IndexOf(dr), "Value is not a valid Date")
        End If
    End Try
Next