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