开发者

Populate the value in datetimepicker from the database

Using VB.NET

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

Code.

开发者_StackOverflow社区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


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


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!

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜