Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

i have a datetime column in sql server and its optional field and if the user decided not to enter then i want to insert the value as NULL in the table and i define something like this:

@deadlineDate datetime = null

when i am inserting into sql server i have this code in asp.net

private DateTime? GetDeadlineDate()
{
    DateTime? getDeadlineDate = null;
    if (!string.IsNullOrEmpty(DeadlineDate.SelectedDate))
    {
       getDeadlineDate = DateTime.Parse(DeadlineDate.SelectedDate).Date;
    }
    if (!getDeadlineDate.HasValue)
    {
        return null;
    }
    return getDeadlineDate.Value;

}

but the problem is: its inserting

1900-01-01 00:00:00.000

in the sql table instead of NULL

what i am doing wrong here?

UPDATE:

private DateTime? GetDeadlineDate()
{
    DateTime? getDeadlineDate = null;
    if (!string.IsNullOrEmpty(DeadlineDate.SelectedDate))
    {
       getDeadlineDate = DateTime.Parse(DeadlineDate.SelectedDate).Date;
    }
    if (!getDeadlineDate.HasValue)
    {
        return DBNull.Value; //throws error....
    }
    return getDeadlineDate.Value;          
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
586 views
Welcome To Ask or Share your Answers For Others

1 Answer

You need DBNull.Value rather than null when inserting into SQL server.

When you set DateTime = null in .NET it takes the minimum value of DateTime which is 01-01-0001.

I'd assume you are using a SMALLDATETIME in SQL Server where the minimum value is '01/01/1900'


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...