0

hey guys i'v been trying to figure it out for 2 days and no luck. i have an observableCollection that stores values and presents them in list box. i want to check item int listbbox(lbBookDetails) and remove it from my collection(myBooks) using delete button.

after i press the delete buttton, i get the element of chosen index,update data for a referenced object inside my chosen Book, and the remove it.

//get chosen book
Book newBook = myBooks.ElementAt(lbBookDetails.SelectedIndex);
//take one book dowfrom authors list
getAuthorByName(newBook.author.fullName()).numOfBooks--; 
//remove the book
myBooks.Remove(myBooks.ElementAt(lbBookDetails.SelectedIndex)); //<--- problem

this line sends an event to selectionChange for some reason,and when it searches for index it gets -1 and i have "Argumentoutofrange exception"

why so?

Ronen
  • 45
  • 6
  • Presumably because you have no selected item. What is the code for `selectionChange()`? – spodger Mar 27 '18 at 11:41
  • Hi thanks for the comment and sorry for the delay this is the code for selectionChange() I'll write it in the comment below – Ronen Apr 05 '18 at 09:21

2 Answers2

0

Why is exception? becouse you remove item which is selected, when u remove selected item from observableCollection then send imformation to listBox that collections was changed and item which is seleted was removed so listbox change selected index on -1 and call event selectedchange.

Tips: in future u have problem with null reference in line

myBooks.Remove(myBooks.ElementAt(lbBookDetails.SelectedIndex)); //<--- problem

u this:

var index = lbBookDetails.SelectedIndex;
myBooks.Remove(myBooks.ElementAt(index ));

Sorry for my English

Haqu
  • 71
  • 3
0

this is the code for selectionChange()

    private void lbBookDetails_SelectionChanged(object sender, SelectionChangedEventArgs e)
    {
        var book = myBooks.ElementAt(lbBookDetails.SelectedIndex) as Book;
        if (book == null)
        {
            return;
        }

        tboAuthor.Text = book.author.fullName();      //displaying the values in case ArgumentOutOfRangeException selection from box
        tboCopies.Text = book.numOfCopys.ToString();
        tboPrice.Text = book.Price.ToString();
        tbonumByAuthor.Text = book.author.numOfBooks.ToString();

    }
Ronen
  • 45
  • 6