c# - linq .Value Nullable Object must have a value. How to skip? -


i have linq code null:

        cbo3.itemssource = empty.union(from in                                            (from b in completedata                                             select b.touropid).distinct()                                        select new comboboxitemstring() { valuestring = a.value.tostring() }); 

but touropid null throwing error on a.value.tostring() . how solve this?

the problem occurs because access value property of nullable type null (or, more precisely, hasvalue property false). how fix depends on want do:

  1. if want filter out items touropid null, add where clause:

    ... (from b in completedata  b.touropid != null         // filter  select b.touropid).distinct() ... 
  2. if want use replacement value, e.g. 0, if touropid null, use null coalescing operator ??, converts int? int:

    ... (from b in completedata  select b.touropid ?? 0).distinct() ... 

    or, alternatively,

    ... select new comboboxitemstring() { valuestring = a.getvalueordefault().tostring() }); 
  3. if want show different combobox entry if touropid null, use ternary operator ?::

    ... select new comboboxitemstring() {      valuestring = (a == null ? "no tour operator" : a.value.tostring()) }); 

    if want show empty string if a null, solution simpler:

    ... select new comboboxitemstring() { valuestring = a.tostring() }); 

    since nullable.tostring returns empty string if not have value.


Comments

Popular posts from this blog

SPSS keyboard combination alters encoding -

Add new record to the table by click on the button in Microsoft Access -

javascript - jQuery .height() return 0 when visible but non-0 when hidden -