Note: Don't care with Connection becuse the connection work. Field in database is DateTime
DateTime dtc = Convert.ToDateTime(dateTimePicker1.Value.Date);
cmd = new SqlCommand("UPDATE LAB_TESTING set Lab_Nam='" + lab_id + "',Rslt_lb='" +
textBox1.Text + "',Tst_Dat='" + dtc + "' Where Lab_ID='" +
bindex + "'", con);
con.Open();
cmd.ExecuteNonQuery();
MessageBox.Show("You Update recored successfully", "delete", MessageBoxButtons.OK, MessageBoxIcon.Information);
dataGridView1.DataSource = null;
con.Close();
readdatagrid1();
after Run program , I got Conversion failed when converting date and/or time from character string.
Don't use string concatenation to build your queries ( SQL injection alert , also read this !). Use parameterized queries . As for your problem: format the date as yyyy-MM-dd
( ISO 8601 ) and it'll work.
If you'd have used parameterized queries correctly you could've just passed in the DateTime as-is and the driver would've ensured the value would get passed correctly to SQL regardless the "format" / locale setting / whatever since the value would be passed as a DateTime instead of a string. Something like this:
cmd = new SqlCommand(@"UPDATE LAB_TESTING set Lab_Nam = @labnam,
Rslt_lb = @result, Tst_Dat = @tstdat
Where Lab_ID = @id", con);
cmd.Parameters.AddWithValue("@labnam", lab_id );
cmd.Parameters.AddWithValue("@result", textBox1.Text);
cmd.Parameters.AddWithValue("@tstdat", dateTimePicker1.Value.Date);
cmd.Parameters.AddWithValue("@id", bindex);
con.Open();
cmd.ExecuteNonQuery();
Other than that I also recommend to wrap the con
and cmd
in a using() { ... }
statement so that you can be sure this stuff gets disposed properly and that you give your variables and fieldnames decent names and use a consistent naming scheme.
Now repeat after me:
I will never, ever, run queries again that have been string-concatenated together anymore!
From now on I will use parameterized queries
If I need to run string-concatenated queries ever again I will make sure all values are escaped properly
Repeat the above aloud, at least 50 times.
Try this
DateTime dtc = Convert.ToDateTime(dateTimePicker1.Value.ToString("dd/MM/yyyy"));
or else
you can also do this
DateTime dtc = Convert.ToDateTime(dateTimePicker1.Text)
If you are getting this error with your SQL code than have a look here
这对你有用。
var date = (DateTime)dateTimePicker1.SelectedDate.Value;
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.