Avatar of IT Genesis
IT Genesis
 asked on

Conversion failed when converting date and/or time from character string

this my error and my code

i have a problem with data fill in database

error is
Conversion failed when converting date and/or time from character string

my data type is date
i put data from text box mode date

Image-1.png
ASP.NETC#Microsoft SQL Server

Avatar of undefined
Last Comment
it_saige

8/22/2022 - Mon
ASKER CERTIFIED SOLUTION
Éric Moreau

THIS SOLUTION ONLY AVAILABLE TO MEMBERS.
View this solution by signing up for a free trial.
Members can start a 7-Day free trial and enjoy unlimited access to the platform.
See Pricing Options
Start Free Trial
GET A PERSONALIZED SOLUTION
Ask your own question & get feedback from real experts
Find out why thousands trust the EE community with their toughest problems.
IT Genesis

ASKER
thanks ^_^
it_saige

Or better yet, rather than trying to concatenate a string into an insert statement, why not parameterize your string and add your parameters using the commands SqlParameter collection; e.g. -
protected void Button1_Click(object sender, EventArgs e)
{
    DateTime date1 = DateTime.ParseExact(Txt_refd.Text, "yyyy-MM-dd", null);
    DateTime date2 = DateTime.ParseExact(Txt_out.Text, "yyyy-MM-dd", null);

    using (var command = new SqlCommand())
    {
        command.CommandText = "INSERT INTO FZMain (ID, NAME, ChassisNO, CarModel, LastOwner, Payment, Cases, Refference, RefferenceDate, OutDate, FamilyRegister) " +
            "VALUES (@ID, @NAME, @ChassisNO, @CarModel, @LastOwner, @Payment, @Cases, @Refference, @RefferenceDate, @OutDate, @FamilyRegister)";
        command.Connection = con;
        command.Parameters.AddWithValue("@ID", Txt_ID.Text);
        command.Parameters.AddWithValue("@NAME", Txt_name.Text);
        command.Parameters.AddWithValue("@ChassisNO", Txt_chasses.Text);
        command.Parameters.AddWithValue("@CarModel", Txt_model.Text);
        command.Parameters.AddWithValue("@LastOwner", Txt_owner.Text);
        command.Parameters.AddWithValue("@Payment", Txt_payment.Text);
        command.Parameters.AddWithValue("@Cases", Drop_case.SelectedValue.ToString());
        command.Parameters.AddWithValue("@Refference", Txt_ref);
        command.Parameters.AddWithValue("@RefferenceDate", date1);
        command.Parameters.AddWithValue("@OutDate", date2);
        command.Parameters.AddWithValue("@FamilyRegister", Txt_femreg.Text);
        // Carry on from this point
    }
}

Open in new window

-saige-
I started with Experts Exchange in 2004 and it's been a mainstay of my professional computing life since. It helped me launch a career as a programmer / Oracle data analyst
William Peck