Leonard Cupat
Leonard Cupat

Reputation: 123

Conversion failed when converting date and/or time from character string. Inserting value from datetimepicker

I have this syntax on my program:

con.Open();
SqlCommand cmdInsert = new SqlCommand();
cmdInsert.Connection = con;
cmdInsert.CommandText =
"INSERT INTO Customers VALUES (@Firstname, @LastName, @Birthdate)";
cmdInsert.Parameters.Add("@Firstname", SqlDbType.VarChar).Value = txtFirstname.Text;
cmdInsert.Parameters.Add("@LastName", SqlDbType.VarChar).Value = txtLastName.Text;
cmdInsert.Parameters.Add("@BIrthdate", SqlDbType.DateTime).Value = dtpBirthdate.Value;

Whenever this code is executed, I get the error

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

I'm guessing that the problem roots from "dtpBirthdate.Value" syntax. I tried looking for a correct format for this part of the syntax but I never got lucky.

ADDITIONAL INFO:

I also changed dtpBirthdate.Value to DBNull.Value and it produces the same error.

Upvotes: 1

Views: 3681

Answers (5)

Leonard Cupat
Leonard Cupat

Reputation: 123

I solved it. What's wrong with my code is the sequence of the parameter variables in my insert statement. It should match the sequence of the columns in my database.

Upvotes: 1

Ravi Kant Singh
Ravi Kant Singh

Reputation: 175

cmdInsert.Parameters.Add("@BIrthdate", SqlDbType.String).Value = dtpBirthdate.Value;

Upvotes: 0

Sudhakar Tillapudi
Sudhakar Tillapudi

Reputation: 26209

Try This:

cmdInsert.Parameters.Add("@BIrthdate", SqlDbType.DateTime).Value =  
                 dtpBirthdate.Value.ToString("yyyy-MM-ddTHH:mm:ss");

Upvotes: 0

Sajeetharan
Sajeetharan

Reputation: 222582

Use the Date property of the returned DateTime:

dateTimePicker1.Value.Date

Upvotes: 2

Yousuf
Yousuf

Reputation: 3275

Try DateTime.Parse(dtpBirthdate.Value)

Upvotes: 0

Related Questions