DNR
DNR

Reputation: 3736

Converting DateTime to DateTime? causing error in asp.net

In my c# code behind, when I convert
public DateTime custDOB { get; set; }
to
public DateTime? SubDOB { get; set; }

I get an error on one of my code lines
tboxDateOfBirth.Text = oCust.custDOB.ToShortDateString();

and the message reads 'System.Nullable' does not contain a definition for 'ToShortDateString' and no extension method 'ToShortDateString' accepting a first argument of type 'System.Nullable' could be found

How can I resolve this issue?

Upvotes: 0

Views: 1317

Answers (3)

Nikhil Agrawal
Nikhil Agrawal

Reputation: 48558

If you are at all time 100% sure that it will have a value and will not be null do this

tboxDateOfBirth.Text = ((DateTime)(oCust.custDOB)).ToShortDateString();

or if there are chances that it can be null you can go for Andre Calil answer.

Also you should read about null-coalescing operator (??).

Upvotes: 1

JleruOHeP
JleruOHeP

Reputation: 10376

There is nullable types - like int? or DateTime?, so you can check, if they have any value with .HasValue To access actual value use

oCust.custDOB.Value.ToShortDateString();

Upvotes: 1

Andre Calil
Andre Calil

Reputation: 7692

Change that line to

tboxDateOfBirth.Text = oCust.custDOB.HasValue? oCust.custDOB.Value.ToShortDateString() : string.Empty;

Upvotes: 8

Related Questions