I am trying to pull data from the table which has a DateTime data type with NULL values.
I am trying to get the required data by using the below method. However, it's throwing an error : ArgumentNullException: Value cannot be null. (Parameter 's')
TermDate = s.TermDate.HasValue ? s.TermDate : DateTime.Parse(s.TermDate.ToString().Replace(null, "-"))
Property: public DateTime? TermDate { get; set; }
Please advise.
Jaimin ShethiyaPosted Mar 11, 2024, 6:19 AM
Hello Satish,
Please try with the below statement.
TermDate = s.TermDate.HasValue ? s.TermDate : DateTime.Parse(Convert.ToString(s.TermDate).Replace(null, "-"))
Thanks
Rohini ParadePosted Mar 8, 2024, 11:41 AM
Here, Add null check for your object 's'. TermDate is null then provide any standard date according to business or
Rafnas T PPosted Mar 6, 2024, 9:33 AM
Hi,
You can try below code
string TermDate = s?.TermDate?.ToString()?? "-";
if termdate is null then string will display as - else will show the date.
Naimish MakwanaPosted Mar 6, 2024, 7:41 AM
The issue here is that you’re trying to call
ToString()on anullvalue. Whens.TermDateisnull,s.TermDate.ToString()will throw anArgumentNullException.If you want to assign a default value when
s.TermDateisnull, you can do so directly in the ternary operator without callingToString()orReplace(). Here’s how you can do it:In this code, if
s.TermDatehas a value, it will be assigned toTermDate. Ifs.TermDateisnull, thenTermDatewill be assigned a default date (in this case, January 1, 1900). You can replacenew DateTime(1900, 1, 1)with any default date you prefer.Thanks
Amit MohantyPosted Mar 6, 2024, 5:31 AM
You should check if s.TermDate is null before trying to access its value.
Sam HobbsPosted Mar 5, 2024, 4:28 PM
You are checking
s.TermDatebut nots. The error message is saying that there is nos. You need to ensure thatsis notnull.