locked
I am getting this Error please help"Conversion failed when converting date and/or time from character string." RRS feed

  • Question

  • User637218400 posted

    conn.Open();
    SqlCommand comm = conn.CreateCommand();
    comm.CommandType = CommandType.Text;
    var DOB = Cdob.SelectedDate;  //C is a calendar
    comm.CommandText = "Insert into Student values('" + txtStudentName.Text + "','" + DOB + "')";

    comm.ExecuteNonQuery();

    conn.Close();
    Response.Redirect("default.aspx");

    Sunday, June 25, 2017 3:57 AM

All replies

  • User632428103 posted

    Hello kris wu,

    replace your variable DOB by a parameter is better , here is it a sample with your code : 

    string connection = ConfigurationManager.ConnectionStrings["TESTSAMPLE"].ConnectionString;
                SqlConnection conn = new SqlConnection(connection);
                conn.Open();
                SqlCommand comm = conn.CreateCommand();
                comm.CommandType = CommandType.Text;
                var DOB = Calendar1.SelectedDate;  //C is a calendar
                comm.CommandText = "INSERT INTO TEST(dateBegin) Values(@datebegin)";
                comm.Parameters.Add(new SqlParameter("@datebegin", Calendar1.SelectedDate));
                
    //
                comm.ExecuteNonQuery();
    
                conn.Close();
                
                
                //Response.Redirect("default.aspx");

    Sunday, June 25, 2017 8:22 AM
  • User-707554951 posted

    Hi Kris Wu

    DataTable in my database:

    CREATE TABLE [dbo].[Student] (
        [StudentName] NVARCHAR(50) NOT NULL,
        [Date]        DATE           NULL, 
        CONSTRAINT [PK_Student] PRIMARY KEY ([StudentName]),
    );
    
    

    Working code:

    string constr = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
                using (SqlConnection conn = new SqlConnection(constr))
                {
                    conn.Open();
                    SqlCommand comm = conn.CreateCommand();
                    comm.CommandType = CommandType.Text;
                    var DOB = Calendar1.SelectedDate;  //C is a calendar
                   comm.CommandText = "Insert into Student values('" + txtStudentName.Text + "','" + DOB + "')";
                    // or use parameter.
                    //comm.CommandText = "Insert into Student values(@StudentName,@registerdate)";
                    //comm.Parameters.AddWithValue("@StudentName", txtStudentName.Text);
                    //comm.Parameters.Add("@registerdate", SqlDbType.Date).Value = DOB;
                    comm.ExecuteNonQuery();
    
                    conn.Close();
                }

    Output screenshot as below:

    Best regard

    Cathy

    Monday, June 26, 2017 7:59 AM