tags:

views:

103

answers:

2

Using VB.NET

I want to display the date in datetimepicker from the database.

Code.

cmd= new sqlcommand("select date from table1", con)
dr = cmd.executereader
while dr.read()
datetimepicker1.value.add(dr("Date"))
end while 
dr.close

But it showing error as specified cast is not valid

How to get a value?

Need vb.net code Help

+1  A: 

You can cast the value to DateTime, the problem is that dr("Date") is a string and in your code your making a string value equal to a DateTime and that's the error your seeing. Try putting

datetimepicker1.value.add(DirectCast(dr("Date"), DateTime))

This should cast the string value to a DateTime value. One thing you might want to add to your code is a check to make sure the value of dr("Date") is actually a date and not some other value type.

Hope this helps!

ajrawson
Another way to get the date value assigned would be to use datetimepicker1.value = DirectCast(dr("Date"), DateTime))
ajrawson
Erm - that's not quite right dr("Date") isn't a string is it? It might default to a string but its an object value if not explicitly typed.
Murph
Murph you are correct, it is an object. My bad, was pulling from memory on that one, thanks for correcting me.
ajrawson
+1  A: 

DateTime.Add doesn't do what you think it does. It adds a TimeSpan (not a date) to an existing date. In your case you have a date, not a timespan, and want to set it on a datimepicker, not add a period of time to it.

You should do this instead:

datetimepicker1.Value = dr("Date")

If dr("Date") is of type Object, you'll need to explicitly convert it to a Date object like this:

datetimepicker1.Value = CDate(dr("Date"))
Meta-Knight