Click here to Skip to main content
15,886,724 members
Please Sign up or sign in to vote.
2.00/5 (1 vote)
See more:
This error points to my combobox extension class. I use a List collection in a 3-layer app that uses a pickListItem.

My comboboxExtension.cs
C#
public static int? SelectedPicklistNullableID(this ComboBox cb)
       {
           if (cb.SelectedItem == null) return null;
           return ((PickListItem)cb.SelectedItem).ID;
       }

       public static int SelectedPicklistID(this ComboBox cb)
       {
           return cb.SelectedPicklistNullableID().Value;
       }


In debug mode, I can see the dropdown list, then select a value, and this error occurs. Do I need to add a List<> to the Items property of the combobox in design? Any help is appreciated. I don't know how to bind to a List. If u need more code, let me know.
Posted
Comments
Philippe Mori 5-Jan-15 17:48pm    
Use a debugger and check which variable is null.

You probably call SelectedPicklistID when no item is selected.

Typically, you check the call stack to see when the method is called and then take the appropriate action.

1 solution

You can use the Value of a nullable type only if the object is not null. If it is null, an exception is thrown. You can first check the object of a nullable type for null before trying to dereferencing it by an attempt to get the value. If the object is not null, you can get Value.

It could be something like this:
C#
int? value = cb.SelectedPicklistNullableID();
if (value == null)
   return -1; // for example;
              // traditional index returned when nothing is selected
else
   return value.Value;

Note that "-1" (more exactly, index less then zero) selection agreement, which is always used in .NET controls with selection, makes nullable type redundant. Alternatively, you can use nullable type everywhere, taking Value only when you actually need to select anything using the index, or unselect or determine if something is selected, but using non-nullable indices is simple, because the agreement is already used.

—SA
 
Share this answer
 
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900