How to assign the null value, null and "" to the DateTime type in the C # and SQL Server databases?

Source: Internet
Author: User
Tags date1

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.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.