Today, when you assign the datetime type data in the database to the datetime type variable in C #, a problem occurs, that is, the datetime data in the database has a null value.
C # by default, null cannot be assigned to the datetime variable, but nullable type datetime can be used. You only need to add? Number, such:
Datetime? X;
X can be assigned a null value.
However, changing from the datetime type of the database to the datetime type of C # requires convert. todatetime (). If the datetime data in the database is null, this method cannot be used.
So I added an if statement:
If (row ["date1"])! = NULL)
However, this If statement is invalid.
Row ["date1"]. tostring ()! = NULL
You still cannot determine whether the datetime-type column date1 in the database is null.
Later changed to row ["date1"]. tostring ()! = "" Can finally be judged. Complete statement:
Datetime? X;
If (row ["date1"]. tostring ()! = "")
X = convert. todatetime (["date1"]);
Else
X = NULL;
Note that in the end, X can only be null, rather than "" as in the original database data "". Because X is declared as a nullable <datetime> type variable.
In this way, if X is saved to the database, the database is shown as 1900-1-1.
The difference between null and "" in C # is that the former does not point to any string object, while the latter is a string object with a length of 0 and allocates memory space for it.
But I just tried it. No matter whether "" or null is stored in the database, it is-1-1. If you want to be null in the database, you can choose when X is null or, do not store related columns in the database.