Vignesh Subramanian
Vignesh Subramanian

Reputation: 7289

converting string to datetime in C# on null value exception

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?

Upvotes: 0

Views: 3593

Answers (3)

mazharenko
mazharenko

Reputation: 635

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?

Upvotes: 1

Yuval Itzchakov
Yuval Itzchakov

Reputation: 149558

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.

Upvotes: 3

Sudhakar Tillapudi
Sudhakar Tillapudi

Reputation: 26209

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

Upvotes: 2

Related Questions