asp conversion of a varchar data type to a datetime error SQL aspx

797 views Asked by At

I don't know what i need to do. I was searching two days and didn't find something helpfull.

fieldValue = row.Cells[0].Text;
DateTime timeNow = DateTime.Now;

string constring = System.Configuration.ConfigurationManager.ConnectionStrings["ITCConnectionString"].ConnectionString;
using (SqlConnection connection = new SqlConnection(constring)) {
    timeNow = Convert.ToDateTime(timeNow);
    using (SqlCommand cmd = new SqlCommand("UPDATE AktywneZgloszenia SET Data_przyjecia_do_realizacji='" + timeNow + "' WHERE Nr_zgloszenia ='"+fieldValue+"';", connection)) {
        using (SqlDataAdapter da = new SqlDataAdapter(cmd)) {
            connection.Open();
            cmd.ExecuteNonQuery(); // <--executeNon
            connection.Close();
            GridView1.DataBind();
        }
    }
}

When i'm trying to save/update variable timeNow i have an error:

The conversion of a varchar data type to a datetime data type resulted in an out-of-range value. The statement has been terminated.

Column in both databases type= datetime variables in dane[] type= string.(not in this fragment) I cleared all data from database. What i'm doing wrong ?

1

There are 1 answers

4
Stan On BEST ANSWER

As Martin Smith hinted, you want to use SQL Command Parameters rather than build the command via concatenation.

Something like:

fieldValue = row.Cells[0].Text;
DateTime timeNow = DateTime.Now;

string constring = System.Configuration.ConfigurationManager.ConnectionStrings["ITCConnectionString"].ConnectionString;
using (SqlConnection connection = new SqlConnection(constring)) {
// timeNow = Convert.ToDateTime(timeNow);  (not needed)
using (SqlCommand cmd = new SqlCommand("UPDATE AktywneZgloszenia SET Data_przyjecia_do_realizacji= @pTimeNow  WHERE Nr_zgloszenia = @pFieldValue;", connection)) {
    using (SqlDataAdapter da = new SqlDataAdapter(cmd)) {
        connection.Open();
    cmd.Parameters.AddWithValue("@pTimeNow", timeNow); // <-- 'pass' timenow
    cmd.Parameters.AddWithValue("@pFieldValue", fieldValue); // <-- 'pass' fieldValue
        cmd.ExecuteNonQuery(); // <--executeNon
        connection.Close();
        GridView1.DataBind();
    }
}

}