tags:

views:

80

answers:

3

Hi

Until recently I had a combo box that was bound to a Linq queried IEnumerable of a DataService.Obj type in the bind method, and all worked fine

private IEnumerable<DataService.Obj> _GeneralList;
private IEnumerable<DataService.Obj> _QueriedList;


private void Bind()
{
    _GeneralList = SharedLists.GeneralList;
    _QueriedList = _GeneralList.Where(q =>q.ID >1000);

    cmbobox.ItemsSource = _QueriedList;
}

Then I had to change the method to insert a new obj and set that object as the default obj and now I get a "System.NullReferenceException: Object reference not set to an instance of an object" exception. I know this has to do with inserting into a linq queried ienumerable but I cant fix it. Any help will be gratefully received.

private IEnumerable<DataService.Obj> _GeneralList;
private IEnumerable<DataService.Obj> _QueriedList;

private void Bind()
{
    _GeneralList = SharedLists.GeneralList;
    _QueriedList = _GeneralList.Where(q =>q.ID >1000);

    cmbobox.ItemsSource = _QueriedList;

    DataService.Obj info = new DataService.Obj();
    info.ID = "0";
    (cmbobox.ItemsSource as ObservableCollection<DataService.Obj>).Insert(0,info);
    cmbobox.SelectedIndex = 0;
}

Thanks in advance

A: 

Try inserting your new item before binding to the control.

private IEnumerable<DataService.Obj> _GeneralList; 
private IEnumerable<DataService.Obj> _QueriedList; 

private void Bind() 
{ 
    _GeneralList = SharedLists.GeneralList; 
    _QueriedList = _GeneralList.Where(q =>q.ID >1000).ToList(); 

    DataService.Obj info = new DataService.Obj(); 
    info.ID = "0"; 
    _QueriedList.Insert(0,info); 

    cmbobox.ItemsSource = _QueriedList; 

    cmbobox.SelectedIndex = 0; 
} 
DaveB
A: 
Mark Synowiec
+1  A: 

This expression :-

(cmbobox.ItemsSource as ObservableCollection<DataService.Obj>)

Will return null. The ItemsSource is what ever was assigned to it. In this case a LINQ supplied object that implements IEnumerable<DataService.Obj> hence the as returns null (LINQ knows nothing of ObservableCollection<T> and certainly doesn't use it).

See this question to create a ToObservableCollection extension method.

That said I'm gonna guess that your actual objective is to have "<N/A>" element at the top of the list right? If so try this:-

 cmbobox.ItemsSource=  Enumerable.Repeat(new DataService.Obj() {ID = 0}, 1)
                     .Union(_QueriedList));

This inserts as single DataService.Obj instance with an ID of 0 as the first item of an IEnumerable<DataService.Obj followed by all the items in _QueriedList. No need to attempt to insert a value into collection with this approach.

AnthonyWJones
I ended up creating an extension method as the .Union method did not work for me. And you were quite right as to why my method was failing and the general purpose of the method.Thanks
Steve