0

I am getting the following error when trying to save registration date in the database. The conversion of a varchar data type to a datetime data type resulted in an out-of-range value. The statement has been terminated.

[WebMethod]
        public bool Attendance(Attendance attendance)
        {
            bool UploadSuccess = false;
            cn.Open();

            SqlCommand com = new SqlCommand("INSERT INTO tblAttendance (StudentID, RegistrationDate) values (" +
                attendance.StudentID + " ,'" +
                attendance.RegistrationDate + "')", cn);
              {
                com.Parameters.AddWithValue("@StudentID", attendance.StudentID);
                com.Parameters.AddWithValue("@RegistrationDate", attendance.RegistrationDate);
                int i = com.ExecuteNonQuery();
                cn.Close();
                if (i != 0)
                {
                    UploadSuccess = true;
                }

                return UploadSuccess;
            }
        }

I am trying to save the current date after the students have successfully registered

  Attendance record = new Attendance();
 record.StudentID = a.StudentID;
  record.RegistrationDate = DateTime.Now;
  • Take a look at this: http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlcommand.parameters(v=vs.110).aspx – Dave Mason Mar 20 '14 at 14:31
  • Out of interest, why do lines 1 and then 4 in the "Save button" code? – Jon Egerton Mar 20 '14 at 14:31
  • 1
    Sounds like your date format is wrong. You can try `SET DATEFORMAT dmy` from [TechNet](http://technet.microsoft.com/en-us/library/ms189491.aspx). – Dave Johnson Mar 20 '14 at 14:41
  • In addition to the command parameter syntax, you need to make sure what type of variables and values you're passing around. If you want to get rid of the time part from the combined date+time.... `DateTime.Today` is the same as `DateTime.Now.Date` - http://stackoverflow.com/questions/7740458/extract-the-date-part-from-datetime-in-c-sharp – AjV Jsy Mar 20 '14 at 15:10
  • What is the data type of the RegistrationDate column in your database? – Chris Dunaway Mar 20 '14 at 15:22

0 Answers0