Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

sqldatetime overflow exception c#.NET

string con = ConfigurationManager.ConnectionStrings["connectionString"].ConnectionString;

        SqlConnection cn = new SqlConnection(con);
        string insert_jobseeker = "INSERT INTO JobSeeker_Registration(Password,HintQuestion,Answer,Date)"
      + " values (@Password,@HintQuestion,@Answer,@Date)";

        SqlCommand cmd = new SqlCommand();
        cmd.Connection = cn;
        cmd.CommandType = CommandType.Text;
        cmd.CommandText = insert_jobseeker;

 cmd.Parameters.Add(new SqlParameter("@Password", SqlDbType.VarChar, 50));
            cmd.Parameters["@Password"].Value = txtPassword.Text;
            cmd.Parameters.Add(new SqlParameter("@HintQuestion", SqlDbType.VarChar, 50));
            cmd.Parameters["@HintQuestion"].Value = ddlQuestion.Text;
            cmd.Parameters.Add(new SqlParameter("@Answer", SqlDbType.VarChar, 50));
            cmd.Parameters["@Answer"].Value = txtAnswer.Text;

            **cmd.Parameters.Add(new SqlParameter("@Date", SqlDbType.DateTime));
            cmd.Parameters["@Date"].Value = System.DateTime.Now**

I got error that

"SqlDateTime overflow. Must be between 1/1/1753 12:00:00 AM and 12/31/9999 11:59:59 PM."

What's the solution for this ?

like image 689
user1676130 Avatar asked Nov 03 '22 01:11

user1676130


1 Answers

Try changing the Type of @Date on the SQL Server side to DATETIME2(7)

Then in your code use this line instead:

cmd.Parameters.Add(new SqlParameter("@Date", SqlDbType.DateTime2)); 

Your code looks okay as shown but possibly something is going on with the conversion due to a localization issue or something wrong with your Region/Time settings so see if this works.

like image 186
jordanhill123 Avatar answered Nov 08 '22 09:11

jordanhill123