Reputation: 333
I've got this error that said String was not recognized as a valid DateTime, can anyone help me what's wrong here?
Dim Br As New BL.Bridge
Me.DataSource = Br.List(DateTime.ParseExact(Me.txtTempo.Text, "dd-MM-yyyy", CultureInfo.InvariantCulture)) 'error is right here
Me.ReportPath = "~/report/JaTem.rpt"
Me.HasPrintButton = True
Me.ShowGroupTree = False
If DataSource.Rows.Count > 0 Then
Me.HasPrintButton = True
Server.Transfer("~/report/rpt.aspx")
Else
lblMessage.Text = "No Data!"
End If
if txtTempo
is filled with date it's work, but when txtTempo
is empty, it's getting error
Upvotes: 1
Views: 16554
Reputation: 54532
The DateTime.ParseExact
method that you are using will give an error when it runs into data that it can't handle. You need to do one of 3 things,
- validate the data before using the ParseExact method
- use exception handling to catch the error and notify your user
- or you can use the
DateTime.TryParseExact
which will give you a Boolean result to indicate if the method succeeded. You would use it something like this.:
Imports System.Globalization
Module Module1
Sub Main()
Dim Date1Data As String = ""
Dim Date2Data As String = "25-09-2015"
Dim result As DateTime
If DateTime.TryParseExact(Date1Data, "dd-MM-yyyy", CultureInfo.InvariantCulture, DateTimeStyles.None, result) Then
'handle it here
Else
Console.WriteLine("Format Error")
End If
If DateTime.TryParseExact(Date2Data, "dd-MM-yyyy", CultureInfo.InvariantCulture, DateTimeStyles.None, result) Then
Console.WriteLine(result) 'handle it here
Else
Console.WriteLine("Format Error")
End If
Console.ReadLine()
End Sub
End Module
or modifying your code something like this should work.
Dim Br As New BL.Bridge
Dim result as Date
If DateTime.TryParseExact(Me.txtJatem.Text, "dd-MM-yyyy", CultureInfo.InvariantCulture, DateTimeStyles.None, result) Then
Me.DataSource = Br.List(result) 'error is right here
Me.ReportPath = "~/report/JaTem.rpt"
Me.HasPrintButton = True
Me.ShowGroupTree = False
If DataSource.Rows.Count > 0 Then
Me.HasPrintButton = True
Server.Transfer("~/report/rpt.aspx")
Else
lblMessage.Text = "No Data!"
End If
Else
lblMessage.Text = "Format Error, please check input and try again"
End If
Upvotes: 1