MyWay
MyWay

Reputation: 1025

Observable Collection and System.ArgumentOutOfRangeException

I got the screen with listbox(listbox takes items from observable collection), where the user can choose item.

this is the code which shows what happens when the user click on the item:

 // method is invoked when we select the element from the list 
        private void ItemsList_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            // getting object which was clicked in the listbox
            dbFoodTable item = Fooditems.ElementAt(ItemsList.SelectedIndex);
            // mark this object as choosenMeal and store it to get it back in next page
            PhoneApplicationService.Current.State["choosen"] = item;
            //going to next page
            NavigationService.Navigate(new Uri("Customization.xaml", UriKind.Relative));            
       }

When I choose the item from listbox I go to next screen where I have all details of this item(like prize, description, name ...), the error shows when I'm backing to this listbox screen.

this line

 dbFoodTable item = Fooditems.ElementAt(ItemsList.SelectedIndex);

is underlined with this info An exception of type 'System.ArgumentOutOfRangeException' occurred in mscorlib.ni.dll but was not handled in user code. This line is in the

ItemsList_SelectionChanged 

method.

It would be perfect if this method wouldn't be even invoked, when I'm backing, but world isn't perfect. I think it works in this way, when we go to other page we selected for example second item and when we backing to this screen this item is not selected any more => selectionchanged => invoking method

How I should solve this problem ?

Upvotes: 1

Views: 966

Answers (1)

T McKeown
T McKeown

Reputation: 12857

Why not make sure that the selectedIndex exists in the list with an "if statement"?

Upvotes: 2

Related Questions