Gopal
Gopal

Reputation: 11972

Populate the value in datetimepicker from the database

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

Upvotes: 0

Views: 7687

Answers (2)

Meta-Knight
Meta-Knight

Reputation: 17845

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"))

Upvotes: 1

ajrawson
ajrawson

Reputation: 1764

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!

Upvotes: 1

Related Questions