Blue Theme Orange Theme Green Theme Red Theme
 
Discover the top 5 tips for understanding .NET Interop
Home | Forums | Videos | Advertise | Certifications | Downloads | Blogs | Interviews | Jobs | Beginners | Training
 | Consulting  
Submit an Article Submit a Blog 
 Jump to
Skip Navigation Links
TechnologyExpand Technology
WebsiteExpand Website
Nevron Chart
Search :       Advanced Search »
Home » WebForms Controls » Enter Null Values for DateTime Column of SQL Server

Enter Null Values for DateTime Column of SQL Server

Inserting a null value to the DateTime Field in SQL Server is one of the most common issues giving various errors. Even if one enters null values the value in the database is some default value as 1/1/1900 12:00:00 AM.

Author Rank :
Page Views : 282037
Downloads : 0
Rating :
 Rate it
Level : Intermediate
   Print Read/Post comments Post a comment  Similar Articles  
   Email to a friend  Bookmark  Author's other articles  
 
Nevron Chart
Become a Sponsor
Discover the top 5 tips for understanding .NET Interop
Become a Sponsor
 Tag Cloud
 Latest Jobs
More ... 
 Latest Interview Questions
More ... 

Introduction:

Inserting a null value to the DateTime Field in SQL Server is one of the most common issues giving various errors. Even if one enters null values the value in the database is some default value as 1/1/1900 12:00:00 AM.

The Output of entering the null DateTime based on the code would in most cases have errors as:

  • String was not recognized as a valid DateTime.
  • Value of type 'System.DBNull' cannot be converted to 'String'.

Or No Error but DataTime entered in Database would be as 1/1/1900 12:00:00 AM
So lets write the code to enter null values in the DataBase.

The User Interface is as follows:

To begin with Code:

Namespaces used

  • System.Data.SqlClient/ System.Data.OleDb
  • System.Data.SqlTypes
  • Code for System.Data.SqlClient

C#

string
sqlStmt ;
string conString ;
SqlConnection cn =
null;
SqlCommand cmd =
null;
SqlDateTime sqldatenull ;
try
{
sqlStmt = "insert into Emp (FirstName,LastName,Date) Values (@FirstName,@LastName,@Date) ";
conString = "server=localhost;database=Northwind;uid=sa;pwd=;";
cn =
new SqlConnection(conString);
cmd =
new SqlCommand(sqlStmt, cn);
cmd.Parameters.Add(
new SqlParameter("@FirstName", SqlDbType.NVarChar, 11));
cmd.Parameters.Add(
new SqlParameter("@LastName", SqlDbType.NVarChar, 40));
cmd.Parameters.Add(
new SqlParameter("@Date", SqlDbType.DateTime));
sqldatenull = SqlDateTime.Null;
cmd.Parameters["@FirstName"].Value = txtFirstName.Text;
cmd.Parameters["@LastName"].Value = txtLastName.Text;
if (txtDate.Text == "")
{
cmd.Parameters ["@Date"].Value =sqldatenull ;
//cmd.Parameters["@Date"].Value = DBNull.Value;
}
else
{
cmd.Parameters["@Date"].Value = DateTime.Parse(txtDate.Text);
}
cn.Open();
cmd.ExecuteNonQuery();
Label1.Text = "Record Inserted Succesfully";
}
catch (Exception ex)
{
Label1.Text = ex.Message;
}
finally
{
cn.Close();
}

VB.NET

Dim sqlStmt As String
Dim
conString As String
Dim
cn As SqlConnection
Dim cmd As SqlCommand
Dim sqldatenull As SqlDateTime
Try
sqlStmt = "insert into Emp (FirstName,LastName,Date) Values (@FirstName,@LastName,@Date) "
conString = "server=localhost;database=Northwind;uid=sa;pwd=;"
cn =
New SqlConnection(conString)
cmd =
New SqlCommand(sqlStmt, cn)
cmd.Parameters.Add(
New SqlParameter("@FirstName", SqlDbType.NVarChar, 11))
cmd.Parameters.Add(
New SqlParameter("@LastName", SqlDbType.NVarChar, 40))cmd.Parameters.Add(New SqlParameter("@Date", SqlDbType.DateTime))
sqldatenull = SqlDateTime.Null
cmd.Parameters("@FirstName").Value = txtFirstName.Text
cmd.Parameters("@LastName").Value = txtLastName.Text
If (txtDate.Text = "") Then
cmd.Parameters("@Date").Value = sqldatenull
'cmd.Parameters("@Date").Value = DBNull.Value
Else
cmd.Parameters("@Date").Value = DateTime.Parse(txtDate.Text)
End If
cn.Open()
cmd.ExecuteNonQuery()
Label1.Text = "Record Inserted Succesfully"
Catch ex As Exception
Label1.Text = ex.Message
Finally
cn.Close()
End Try

Code for System.Data.SqlClient.

C#

string sqlStmt;
string conString ;
OleDbConnection cn =
null ;
OleDbCommand cmd =
null ;
try
{
sqlStmt = "insert into Emp (FirstName,LastName,Date) Values (?,?,?) ";
conString = "Provider=sqloledb.1;user id=sa;pwd=;database=northwind;data source=localhost";
cn =
new OleDbConnection(conString);
cmd =
new OleDbCommand(sqlStmt, cn) ;
cmd.Parameters.Add(
new OleDbParameter("@FirstName", OleDbType.VarChar, 40));
cmd.Parameters.Add(
new OleDbParameter("@LastName", OleDbType.VarChar, 40));
cmd.Parameters.Add(
new OleDbParameter("@Date", OleDbType.Date));
cmd.Parameters["@FirstName"].Value = txtFirstName.Text;
cmd.Parameters["@LastName"].Value = txtLastName.Text;
if ((txtDate.Text == "") )
{
cmd.Parameters["@Date"].Value = DBNull.Value;
}
else
{
cmd.Parameters["@Date"].Value = DateTime.Parse(txtDate.Text);
}
cn.Open();
cmd.ExecuteNonQuery();
Label1.Text = "Record Inserted Succesfully";
}
catch (Exception ex)
{
Label1.Text = ex.Message;
}
finally
{
cn.Close();


VB.NET

Dim
sqlStmt As String
Dim
conString As String
Dim
cn As OleDbConnection
Dim cmd As OleDbCommand
Try
sqlStmt = "insert into Emp (FirstName,LastName,Date) Values (?,?,?) "
conString = "Provider=sqloledb.1;user id=sa;pwd=;database=northwind;data source=localhost"
cn =
New OleDbConnection(conString)
cmd =
New OleDbCommand(sqlStmt, cn)
cmd.Parameters.Add(
New OleDbParameter("@FirstName", OleDbType.VarChar, 40))cmd.Parameters.Add(New OleDbParameter("@LastName", OleDbType.VarChar, 40))cmd.Parameters.Add(New OleDbParameter("@Date", OleDbType.Date))cmd.Parameters("@FirstName").Value = txtFirstName.Text
cmd.Parameters("@LastName").Value = txtLastName.Text
If (txtDate.Text = "") Then
cmd.Parameters("@Date").Value = DBNull.Value
Else
cmd.Parameters("@Date").Value = DateTime.Parse(txtDate.Text)
End If
cn.Open()
cmd.ExecuteNonQuery()
Label1.Text = "Record Inserted Succesfully"
Catch ex As Exception
Label1.Text = ex.Message
Finally
cn.Close()
End Try

The Data Entered in DataBase:

Comment Request!
Thank you for reading this post. Please post your feedback, question, or comments about this post Here.
Login to add your contents and source code to this article
 [Top] Rate this article
 
 About the author
 
Sushila Patel
Microsoft .NET MVP
Looking for C# Consulting?
C# Consulting is founded in 2002 by the founders of C# Corner. Unlike a traditional consulting company, our consultants are well-known experts in .NET and many of them are MVPs, authors, and trainers. We specialize in Microsoft .NET development and utilize Agile Development and Extreme Programming practices to provide fast pace quick turnaround results. Our software development model is a mix of Agile Development, traditional SDLC, and Waterfall models.
Click here to learn more about C# Consulting.
 
Introducing MaxV - one click. infinite control. Hyper-V Hosting from MaximumASP.
Finally – a virtual platform that delivers next-generation Windows Server 2008 Hyper-V virtualization technology from a managed hosting partner you can truly depend on. Visit www.maximumasp.com/max for a FREE 30 day trial. Hurry offer ends soon. Climb aboard the MaxV platform and take advantage of High Availability, Intelligent Monitoring, Recurrent Backups, and Scalability – with no hassle or hidden fees. As a managed hosting partner focused solely on Microsoft technologies since 2000, MaximumASP is uniquely qualified to provide the superior support that our business is built on. Unparalleled expertise with Microsoft technologies lead to working directly with Microsoft as first to offer IIS 7 and SQL 2008 betas in a hosted environment; partnering in the Go Live Program for Hyper-V; and product co-launches built on WS 2008 with Hyper-V technology.
Dynamic PDF
ceTE software specializes in components for dynamic PDF generation and manipulation. The DynamicPDF™ product line allows you to dynamically generate PDF documents, merge PDF documents and new content to existing PDF documents from within your applications.
Discover the top 5 tips for understanding .NET
Ricky Leeks presents the top 5 tips for understanding .NET Interoperability. Learn more.
Nevron Chart for .NET 2010.1 Now Available
The leading .NET charting control now features PDF, Flash and Silverlight export, visualization of large datasets and more. Deliver true charting functionality to your BI, Scorecard, Presentation or Scientific apps. Download evaluation now.
ASP.NET 4 Hosting
Get 2 Months Free of ASP.NET Hosting for Only $4.95/month! Receive FREE MS SQL and MySQL Databases Including ASP.NET 4/3.5, MVC 3.0, Silverlight 4, Windows 2008/IIS 7.0 Plus FREE IIS 7 Modules. Host UNLIMITED ASP.NET Web Sites – Click Here!
 
 Post a Feedback, Comment, or Question about this article
Subject:
Comment:
Nevron Chart
Become a Sponsor
 Comments
NULL Times but Date entered by Daniel On October 31, 2007
I was able to produce code that would NULL a full datetime if a user didn't enter a date, but what if I've broken up my datetime field into two controls (a date and a time control) and they enter a date but no time? Currently I get for example: 1/10/2007 00:00:00.000, but when they save the data and come back to the form, the time is no longer NULL or empty, but rather 12:00 AM. How can I get it to STAY empty (NULL)? I currently use another field in conjuction, called NULLTime (ex: AdmitDateTime and AdmitNULLTime) if the user enters no time, then the NULLTime field is hidden and checked, but indicates that even though the datetime field is showing 12:00 AM, don't show it in the interfaces or reports. I'd rather have a more simple answer, however. I user VB.NET by the way. My email is danielp@obix.net
Reply | Email | Modify 
How to compare NULL with DateTime by Vikram On October 14, 2009
Hi,
    I used above example in my application. I can insert null in my Datetime column. But now I want query my table against Date column, so how i compare Datetime with NULL. I tried by comparing directly with NULL it doesn't work. Any other way to achieve this.

Thanks


Reply | Email | Modify 
Thanks a lot by rajitha On October 22, 2009
Hi This article helped me alot. I was trying to update the details by passing parameters to a stored procedure. I couldn't find a solution to pass null value to a stored procedure.
This code helped in solving my problem. Thanks.
Reply | Email | Modify 
Good Article by Vijay On November 26, 2009
It's handy.
Reply | Email | Modify 
thx for share article by Sajjad On August 25, 2010
Hello Sushila Patel
Thx for share his knowledge which is very helpful for me to solve his problem after lot time to wast to search about that.

Sajjad Ahmed
Software Developer
ITBeams(Pvt) Ltd. Lahore
Pakistan

Reply | Email | Modify 
Unable to add null or Insert record ...Please, help... by jimmy On March 5, 2011
I am unable to add null or Insert record using this code..Please, help... Lettle help would much appreciate. I am new to asp.net also... Dim sqlStmt As String Dim conString As String Dim cn As OracleConnection Dim cmd As OracleCommand Dim sqldatenull As OracleDate Try sqlStmt = "insert into temp (startdate, enddate) Values (@startdate, @enddate)" 'conString = "server=localhost;database=Northwind;uid=sa;pwd=;" conString = "Data Source=abc; User Id=abc;Password=ab" cn = New OracleConnection(conString) cmd = New OracleCommand(sqlStmt, cn) 'cmd.Parameters.Add(New sqlParameter("@FirstName", SqlDbType.NVarChar, 11)) 'cmd.Parameters.Add(New SqlParameter("@LastName", SqlDbType.NVarChar, 40)) 'cmd.Parameters.Add(New SqlParameter("@Date", SqlDbType.DateTime)) cmd.Parameters.Add(New OracleParameter("@startdate", OracleDbType.TimeStamp)) cmd.Parameters.Add(New OracleParameter("@enddate", OracleDbType.TimeStamp)) sqldatenull = OracleDate.Null 'cmd.Parameters("@FirstName").Value = txtFirstName.Text 'cmd.Parameters("@LastName").Value = txtLastName.Text If (txtEndDate.Text = "") Then cmd.Parameters("@EndDate").Value = sqldatenull 'cmd.Parameters("@Date").Value = DBNull.Value Else cmd.Parameters("@EndDate").Value = DateTime.Parse(txtEndDate.Text) End If cn.Open() cmd.ExecuteNonQuery() 'Label1.Text = "Record Inserted Succesfully" Catch ex As Exception 'Label1.Text = ex.Message Finally 'cn.Close() End Try
Reply | Email | Modify 
Nevron Chart
 © 2012  contents copyright of their authors. Rest everything copyright Mindcracker. All rights reserved.