In a previous question:
Getting "This method or property cannot be called on Null values" error
I had a problem with the following code:
client_group_details.Add(new ClientGroupDetails(
reader.GetString(Col2Index),
reader.GetString(Col3Index)));
Where I was getting the following error:
Data is Null. This method or property cannot be called on Null values.
This problem was resolved using the following code:
client_group_details.Add(new ClientGroupDetails(
reader.IsDbNull(Col2Index) ? null : reader.GetString(Col2Index),
reader.IsDbNull(Col3Index) ? null : reader.GetString(Col3Index)));
I now have a similar problem with GetDateTime
and GetInt32
, as example is:
client_group_details.Add(new ClientGroupDetails(
reader.GetString(Col2Index),
reader.GetString(Col3Index),
reader.GetDateTime(Col4Index)));
I tried using the following to resolve this problem, but it didn't work
client_group_details.Add(new ClientGroupDetails(
reader.IsDbNull(Col2Index) ? null : reader.GetString(Col2Index),
reader.IsDbNull(Col3Index) ? null : reader.GetString(Col3Index),
reader.IsDbNull(Col2Index) ? null : reader.GetDateTime(Col4Index)));
It gives the error:
Compiler Error Message: CS0173: Type of conditional expression cannot be determined because there is no implicit conversion between '<null>' and 'System.DateTime'
After searching for a solution, I found: Nullable type issue with ?: Conditional Operator. But when I try to use that code, I keep getting ) expected
.
How would I resolve this problem?
DateTime
is a struct
and therefore a value type and cannot be null
. Only reference types and Nullable<T>
(or T?
) types can be null. You have to use a Nullable<DateTime>
. This can also be written as DateTime?
.
DateTime? dt = null;
dt = DateTime.Now;
if (dt.HasValue) ...
if (dt == null) ...
DateTime x = dt.Value;
dt = reader.IsDBNull(Col2Index) ? (DateTime?)null : reader.GetDateTime(Col4Index);
You are missing a closing bracket somewhere.
client_group_details.Add(new ClientGroupDetails(
reader.IsDbNull(Col2Index) ? null : reader.GetString(Col2Index),
reader.IsDbNull(Col3Index) ? null : reader.GetString(Col3Index),
reader.IsDbNull(Col2Index) ? null : reader.GetDateTime(Col4Index)));
Should probably change to
client_group_details.Add(new ClientGroupDetails(
reader.IsDbNull(Col2Index) ? null : reader.GetString(Col2Index),
reader.IsDbNull(Col3Index) ? null : reader.GetString(Col3Index),
reader.IsDbNull(Col2Index) ? (DateTime?)null : reader.GetDateTime(Col4Index)));
or something similar. Depending on your exact code someone will be able to tell you where the missing bracket it.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With