0

how do I insert a datetimepicker date into sql server from vb.net.

Example of my code , just a piece, where birthdate is the datetimepicker control

this is my code for

            cmd1.Parameters.AddWithValue("@Birthdate", birthdate.Value)

and here is the insert into command:

("Insert into [BD_maest].[dbo].[cust] ([Birthdate]) values ('" + birthdate.value + "')", conec)

I'm getting this error when trying to save data: conversion failed when converting date and/or time from character string

Thanks in advance

TecZr
  • 33
  • 2
  • 11

1 Answers1

0

The date string you are passing to sql is not in a format sql will recognise. You could cast value to a DateTime object and use the date time in your sql command. Here is an example (using a parameter for the birthdate - which you probably want to do)

Dim Birthdate As New System.DateTime(YYYY, MM, DD)
Dim sql as String ="Insert into [BD_maest].[dbo].[cust] ([Birthdate]) values ('@birthdate')", conec).
cmd.Connection = conec
cmd.CommandType = CommandType.Text
cmd.CommandText= sql
cmd.Parameters.AddWithValue('birthdate',Birthdate)
cmd.ExecuteNonQuery()

Or make sure your birthDate value is in the form YYYYMMDD which will be understood by sql server:

("Insert into [BD_maest].[dbo].[cust] ([Birthdate]) values ('" + YYYYMMDD + "')", conec).

see this question for more options: Sql query to insert datetime in SQL Server

Community
  • 1
  • 1
iceburg
  • 1,768
  • 3
  • 17
  • 25
  • Thank you @iceburg, it has been much help. I did this and it worked: birthdate.Value.ToString("yyyyMMdd") – TecZr Jun 19 '14 at 23:04