Click here to Skip to main content
15,910,773 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I inserted datetime picker value to database. but I want to edit that value throw c# and update. but I am facing Some errors while updating "Conversion failed. When converting date/or time from character string". My Code is
"UPDATE [dbo].[tempsales] SET[date] = '" + Convert.ToDateTime(dateTimePicker1.Value) + "', [customername]='" + txtcust.Text + "',[billno]='" + txtbno.Text + "',[itemname]='"+txtName.Text+"',[qty]='"+txtQty.Text+"',[price]='"+txtPrice.Text+"',[tax]='"+txtTax.Text+"',[itemtot]='"+txtTotal.Text+"' WHERE sno='" + txtslno.Text + "'", con);


what can I do now.

What I have tried:

I googled for updating. but find only Insert.
Posted
Updated 15-Apr-17 2:46am
v2
Comments
F-ES Sitecore 15-Apr-17 8:21am    
What field type is "date"?
vijay_bale 15-Apr-17 8:34am    
defaullt date time picker so it is string maybe
[no name] 15-Apr-17 8:31am    
If you used a proper parameterized query instead of this SQL injection attack waiting to happen, you likely wouldn't be having the problem.
vijay_bale 15-Apr-17 9:43am    
@NotPolitcally, It is worked now. Updating. But if I edited one value of one field and click on button for update one new record is adding not updating current record. Where I did wrong.If I touched value of that field only this is happining.
[no name] 15-Apr-17 19:05pm    
"Where I did wrong", and how would you think I would know? I don't have a crystal ball that allows me to see your screen.

Not like that! Never concatenate strings to build a SQL command. It leaves you wide open to accidental or deliberate SQL Injection attack which can destroy your entire database. Use Parametrized queries instead.

You want something along the lines of:
using (SqlConnection con = new SqlConnection(strConnect))
    {
    con.Open();
    using (SqlCommand com = new SqlCommand("UPDATE myTable SET myColumn1=@C1, myColumn2=@C2 WHERE RowId=@ID", con))
        {
        com.Parameters.AddWithValue("@ID", id);
        com.Parameters.AddWithValue("@C1", myTextBox.Text);
        com.Parameters.AddWithValue("@C2", myDateTimePicker.Value);
        com.ExecuteNonQuery();
        }
    }
 
Share this answer
 
Never ever concatenate values directly to the SQL statement. One problem is the data type conversion issue you have faced but you're also vulnerable to SQL injections.

Have a look at Properly executing database operations[^]
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900