Articles → .NET → Conversion of a varchar data type to a datetime data type resulted in an out-of-range value

Conversion of a varchar data type to a datetime data type resulted in an out-of-range value








Software requirement




  1. Visual studio 2005(or above) is installed on your machine.
  2. SQL Server 2008(or above) is installed on your machine.

Prerequisite knowledge




  1. Basics about SQL objects like tables.
  2. Basics about C#.
  3. How to create tables in SQL server and how to insert data into the table?
  4. How to create a project using visual studio?
  5. Basic knowledge about basic controls like button textbox etc and their events.
  6. How to connect to SQL server database using ADO.NET objects.

Steps of execution




  1. Create a new table
  2. Create a new project
  3. Add controls on the page
  4. Add code to insert data in database table.



Create a new table




Picture showing the sample table used in the article

Click to Enlarge


Create a new project




Picture showing the sample asp.net project in visual studio

Click to Enlarge


Add controls on the page




Picture showing the sample screen with 2 textboxes and one button

Click to Enlarge


Add code to insert data in database table




protected void btnInsert_Click(object sender, EventArgs e) {
  using(SqlConnection connection = new SqlConnection("connection_string")) {
    // Open a connection
    connection.Open();
    string query = string.Empty;
    if (string.IsNullOrEmpty(txtDOB.Text)) query = string.Format("insert into Employee values('{0}','{1}')", txtEmployeeName.Text, DateTime.MinValue);
    else query = string.Format("insert into Employee values('{0}','{1}')", txtEmployeeName.Text, Convert.ToDateTime(txtDOB.Text));

    using(SqlCommand command = new SqlCommand(query, connection)) {
      command.ExecuteNonQuery();
    }
  }
}






Picture showing the out-of-range error message when user enters DateTime.MinValue value

Click to Enlarge




Posted By  -  Karan Gupta
 
Posted On  -  Friday, April 26, 2013

Query/Feedback


Your Email Id  
 
Subject 
 
Query/FeedbackCharacters remaining 250