I have some linq code that is sometimes null:
cbo3.ItemsSource = empty.Union(from a in
(from b in CompleteData
select b.TourOpID).Distinct()
select new ComboBoxItemString() { ValueString = a.Value.ToString() });
But TourOpID is sometimes null throwing an error on a.Value.ToString() . How do I solve this?
The problem occurs because you access the Value property of a Nullable type which is null (or, more precisely, whose HasValue property is false). How to fix this depends on what you want to do:
If you want to filter out items where TourOpID is null, just add a where clause:
...
(from b in CompleteData
where b.TourOpID != null // filter
select b.TourOpID).Distinct()
...
If you want to use a replacement value, e.g. 0, if TourOpID is null, use the null coalescing operator ??, which converts your int? into an int:
...
(from b in CompleteData
select b.TourOpID ?? 0).Distinct()
...
or, alternatively,
...
select new ComboBoxItemString() { ValueString = a.GetValueOrDefault().ToString() });
If you just want to show a different ComboBox entry if TourOpID is null, use the ternary operator ?::
...
select new ComboBoxItemString() {
ValueString = (a == null ? "no tour operator" : a.Value.ToString())
});
If you want to show the empty string if a is null, the solution is even simpler:
...
select new ComboBoxItemString() { ValueString = a.ToString() });
since Nullable.ToString returns an empty string if it does not have a value.
use where
from b in CompleteData where b.TourOpID != null select b.TourOpID
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