title: SQL Server DateTime Accept NULL
body: <p>I've tried to make my code as compact as possible.</p>
  
  <p>Using Microsoft SQL Server, .NET 2.0</p>
  
  <p>I have a date field in my database which accepts null values</p>
  
  <pre><code>LeaseExpiry(datetime, null)
  </code></pre>
  
  <p>I grab the value of the the textbox and convert it to datetime.  </p>
  
  <pre><code>DateTime leaseExpiry = Convert.ToDateTime(tbLeaseExpiry.Text);
  
  INSERT_record(leaseExpiry);
  </code></pre>
  
  <p>The problem I'm having is if the form is submitted and the textbox is empty. I get this error back:</p>
  
  <blockquote>
    <p><em>String was not recognized as a valid DateTime.</em></p>
  </blockquote>
  
  <p>How do I set my code up so that if the textbox is empty, the row is created in the database with <code>NULL</code>?</p>
  
  <p>I've tried initializing my variable to NULL but get an error in Visual Studio</p>
  
  <pre><code>DateTime leaseExpiry = null;
  </code></pre>
  
  <blockquote>
    <p><em>Cannot convert null to 'System.DateTime' because it is a non-nullable value type.</em></p>
  </blockquote>
  
  <p>Here's the Data Access Layer if that helps</p>
  
  <pre><code>public string INSERT_record(DateTime leaseExpiry)
  {
       //Connect to the database and insert a new record 
       string cnn = ConfigurationManager.ConnectionStrings[connname].ConnectionString;
  
       using (SqlConnection connection = new SqlConnection(cnn))
       {
          string SQL = string.Empty;
          SQL = "INSERT INTO [" + dbname + "].[dbo].[" + tblAllProperties + "] ([LeaseExpiry]) VALUES (@leaseExpiry);
  
           using (SqlCommand command = new SqlCommand(SQL, connection))
           {
                  command.Parameters.Add("@leaseExpiry", SqlDbType.DateTime);
                  command.Parameters["@leaseExpiry"].Value = leaseExpiry;
           }
  
           try
           {
                  connection.Open();
                  command.ExecuteNonQuery();
                  return "Success";
           }
           catch (Exception ex)
           {
                  return ex.Message;
           }
       }
  }
  </code></pre>
  
  <p>Thank you</p>