InvalidCastException when parsing dates in VB.NET - vb.net

I'm trying to Parse dates entered into a TextBox into a DateTime value but I keep getting an exception in the TryParseExact method. What I'm trying to do is:
DateTime.TryParseExact(tbAddDate.Text.Trim, "yyMMdd", New CultureInfo("sv-SE"), DateTimeStyles.None, row.Date)
This throws an InvalidCastException with the message "Conversion from type 'DBNull' to type 'Date' is not valid." I realize what is happening is that it's trying to set row.Date to DBNull which is not a valid value for a DateTime. What I don't understand is why it's trying to do this, as the documentation states that it should be set to MinValue and not DBNull.
As a sidenote, I know that I can get around a lot of these problems by using a DateTimePicker but the customer feels that they are very clunky as it's not possible to enter the dates directly with the keyboard.

It seems that (as magnifico's comment suggests) the problem is strictly related to the fact you're passing row.Date as the result argument. It must occur when the code attempts to assign row.Date with Date.MinValue (unless the documentation is inaccurate, which is less likely in this scenario).
I'd advise that you pass some different result argument, and use its value to update row.Date after calling TryParseExact. It might not be the ultimate permanent solution, but it should help you inspect this bug and find the cause to the InvalidCast exception.
Sidenote: perhaps this row.Date doesn't accept Date.MinValue as a legitimate value, i.e.: row.Date might be willing to accept only dates from 01/01/2000 onwards, and Date.MinValue returns 01/01/0001.

Related

If - Strange Behavior in Detecting Type

I discovered this strange behavior in VB.Net today in trying to work with nullable DateTime data. I am pulling a DateTime value out of an XML file for inserting into a database, and I want to allow for an empty value. So I thought I should use If to prevent casting errors:
Dim LastRun As DateTime? = _
If(rowData("LastRun") = "", Nothing, CType(rowData("LastRun"), DateTime))
It seems like this should return a value of Nothing in the case that the If is false, or a value of the date time from LastRun if the value is not blank. Instead, when the If condition returns false, I get a value of DateTime.MinValue, which causes an exception on insert to the database due to SQL DateTime underflow.
I was able to fix it by using DateTime? as the cast in the last parameter, but this behavior seems odd to me. The expected type is clearly DateTime? because that's the variable type. Also, the narrowest type that can allow for both possible result values is DateTime?, since it could be either a DateTime or Nothing. And yet somehow it decides that the result value should be DateTime and then I guess typecasts Nothing to DateTime.MinValue? What is going on here?
Part of the problem is I'm used to C#, and the equivalent expression rowData["LastRun"] == "" ? null : (DateTime)rowData["LastRun"]) doesn't even compile (as expected), because there's "no implicit conversion between DateTime and null."
Nothing is not the same as null in C#, it is a mixture between null and default(T). So when you use Nothing on a value type(like the structure DateTime) you get it's default value what is DateTime.MinValue.

Typed DataSet - InvalidCastException

I've got a typed dataset. I bind the data with a binding source to a form with arround 200 textboxes, dataedits and so on. Everything works fine with one exception:
In my database I have empty DateTimes (DBNull.Value). And when they get bound to a DateEdit-Control, I get the following exceptions:
A first chance exception of type 'System.InvalidCastException' occurred in Microsoft.VisualBasic.dll
A first chance exception of type 'System.Data.StrongTypingException' occurred in myTestDLL.dll
I tried to change the NullValue-Property in the DataSet-Desinger to something else as 'Throw Exception', but it doesn't work for a DateTime. For other types like Integer or String it works fine.
I dont know a nice solution (right now I fill the empty dates with some dummy date and make it invisible in the DateEdit-Control, but this is very uncool) and I hope to find some help here.
It seems that many people got the same problem but I didn't find a solution :(
Why not just skip if test fail ?
if dMyDate is dbnull.value then 'skip, msgbox, set to date.minValue, whatever

VB.Net is my issue with DataRow.IsNull or Format(datetimevalue,"T")?

I am working on a new ASP.Net 4.0 data driven app. In the DAL I check for NULL values on all my data and default to the proper data when NULL. I have a strange issue going on. Two dates are coming back - on one I need the time only. The First line of code for the full date works without fail - but the second line of code errors pointing to the format string but the strange part is that it errors on NULL values which does not use the format string and just returns Date.MinValue. When the second line gets data it formats the return correctly.
Dim dr As DataRow
.TourDate = IIf(dr.IsNull("tourdate"), Date.MinValue, Format(dr("tourdate"), "MM/dd/yyyy"))
.TourTime = IIf(dr.IsNull("tourtime"), Date.MinValue, Format(dr("tourtime"), "T"))
The error comes on the second line when dr("tourtime") is NULL - the erroe is: Argument 'Expression' is not a valid value.
IIf in VB.Net does not do short-circuit evaluation, so the Format call is being executed even if the value is null.
You need to use If:
.TourTime = If(dr.IsNull("tourtime"), Date.MinValue, Format(dr("tourtime"), "T"))
This is the same issue described here: Using VB.NET IIF I get NullReferenceException
To trouble-shoot this, I would inspect the actual value stored. A datetime column that appears to be null may actually have a value.
I think you should use IsDbNull instead of IsNull.

When is it necessary to convert data types in Visual Basic 2010

Visual Basic 2010 (Express). I can best give this by example...
If I take a string from a textbox and assign it to an integer variable, I'm under the impression that you're supposed to use CInt to explicitly convert the contents to an integer.
intMyCount = CInt(txtUserInput.Text)
However, if I don't do that, it still seems to work. Similarly, if I have an integer and concatenate it into a label's text property, it still works:
lblResults.Text = intMyCount & " number of times."
rather than using intMyCount.ToString.
Why does it work? Is VB doing implicit conversions when possible? Are there examples where not explicitly converting with .ToString or using CInt would cause unexpected results?
This is done using late-binding, and it's dangerous because if the conversion ever fails (and there's lots of cases where your first example could fail) it ends up in an exception at runtime. To get the compiler to enforce safer casting, turn Option Strict On.
Additionally, most of the time you don't want to use CInt() to convert your string to int. Instead, prefer Integer.Parse() or Integer.TryParse().
Some languages handle string concatenation easily like this for the non-casting to string. Some also handle non-casting to numeric types to do calculations. Some languages don't handle it at all. However as a best-practice, I would always cast the variable to the type you want to avoid issues with improper input types.

Reporting Services - handling an empty date?

Hey, I have a report parameter which looks like this: 01.01.2009 00:00:00
Its a date (as string), as you might have guessed :). The problem is, this param can be an empty string as well. So I tried those expressions:
=IIf(IsDate(Parameters!DateTo.Value), CDate(Parameters!DateTo.Value), "")
=IIf(Len(Parameters!DateTo.Value) > 0, CDate(Parameters!DateTo.Value), "")
Both dont work and the value for the textfield where I print the expressions result is always #Error. As soon as I remove the CDate stuff, it works, but I have to use it. IS there another way to achieve that? What I want is to display nothing if its not a date or the date (format dd.mm.yyyy) if its a date.
Ideas?
Thanks :)
All arguments to the IIf are evaluated, which results in your error, since the CDate will fail for an empty string.
You can get around this by just writting a function along these lines, using a standard if statement:
Function FormatDate(ByVal s As String) As String
If (s <> "") Then
Return CDate(s).ToString()
Else
Return ""
End If
End Function
Then call it with: =Code.FormatDate(Parameters!DateTo.Value)
First, fix your database to properly store dates rather than doing these workarounds. You probably have bad data in there as well (Feb 30 2010 for example or my favorite, ASAP). Truly there is no excuse for not fixing this at the database level where it needs to be fixed except if this is vendor provided software that you can't change (I would yell at them though, well notify them really, and ask them to fix their data model or go to a new product designed by someone who knows what they are doing. A vendor who can't use dates properly is likely to have software that is very poor all around).
In the query that you use to select the infomation, have you considered just converting all non-dates to null?