Isuru
Isuru

Reputation: 31283

Displaying the time from database in a DateTimePicker

I have a column (datatype is time(7)) in my SQL Server database to store the time. When I try to retrieve that value from the database and display it in a DateTimePicker (format set to display time only), it throws an InvalidCastException error.

This is the line where the casting happens.

r = com.ExecuteReader();
dtpOutTime.Value = (DateTime)r["OutTime"];

I can understand why the error is thrown but I can't figure out a way to correct it.

How can I display only the time from database in a DateTimePicker?

Thank you.

Upvotes: 1

Views: 2416

Answers (1)

Tim Schmelter
Tim Schmelter

Reputation: 460108

For System.Data.DbType.Time you use the .NET Framework type System.TimeSpan.

for example:

dtpOutTime.Value = DateTime.Today + (TimeSpan)r["OutTime"];

(if you want to add the TimeSpan to Today midnight and the timespan would be 6 hours, the result would be 10/22/2012 6:00:00 AM)

Upvotes: 1

Related Questions