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.