0

I use the below code

 extensionRequest[i].EndDate = DateTime.Parse(dsResult.Tables[0].Rows[i]["ActualEndDate"].ToString()); extensionRequest[i].ExtendedEndDate = DateTime.Parse(dsResult.Tables[0].Rows[i]["ExtendedEndDate"].ToString()); extensionRequest[i].ReceivedDate =Convert.ToDateTime(dsResult.Tables[0].Rows[i]["dReceivedOn"].ToString()); 

this works fine when values are coming from the DB but when NULL values are returned it throws an exception!!

Should i check values for all three values like the code below

if (dsResult.Tables[0].Rows[i]["dReceivedOn"].ToString()==null){ extensionRequest[i].ReceivedDate=""; } else{ extensionRequest[i].ReceivedDate =Convert.ToDateTime(dsResult.Tables[0].Rows[i]["dReceivedOn"].ToString()); } 

or i should assign all dates to null on exception?!

is there any other way to do in single line? like tryparse or something?

1

3 Answers 3

3

I'll try being creative. You can create a Nullable TryParse as an Extension Method edition:

public static DateTime? TryParseNullable(this DateTime dateTime, string val) { DateTime outValue; return DateTime.TryParse(val, out outValue) ? (DateTime?) outValue : null; } 

and then use:

extensionRequest[i].EndDate = DateTime.TryParseNullable(dsResult.Tables[0].Rows[i]["ActualEndDate"].ToString()); 

and that can be your one liner.

Sign up to request clarification or add additional context in comments.

Comments

2

You can use DateTime.TryParse() method which returns true on successfull conversion otherwise returns false.

Note: calling ToString() on null throw NullReferenceException hence you need to check for null value before conversion.

Try This:

 if(dsResult.Tables[0].Rows[i]["ActualEndDate"] != null) DateTime.TryParse(dsResult.Tables[0].Rows[i]["ActualEndDate"].ToString(), out extensionRequest[i].EndDate); 

1 Comment

if dsResult.Tables[0].Rows[i]["ActualEndDate"] is null calling ToString will throw execption
1

You can check if value is null like this

extensionRequest[i].EndDate = Convert.IsDbNull(dsResult.Tables[0].Rows[i]["ActualEndDate"]) ? null : Convert.ToDateTime(dsResult.Tables[0].Rows[i]["ActualEndDate"]); 

I'm sure .ToString() is not required.

It will be more readable if you cache a row to the local variable:

var row = dsResult.Tables[0].Rows[i]; ... extensionRequest[i].EndDate = Convert.IsDbNull(row["ActualEndDate"]) ? null : Convert.ToDateTime(row["ActualEndDate"]); 

Be sure .EndDate and others allow null values. In other words, that is DateTime?

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.