Removing an item from a list in Xamarin forms

700 Views Asked by At

The issue i'm having is when I delete a row from my list in Xamarin forms, I have it set up so when the user wants to delete something, they will get a pop up asking if they really want to delete. If they push yes it removes the item from the list..(not a problem) but if the user says no it still removes the item (temperately) you then refresh the page and it will come back. I am wondering what I have wrong in my code. so it doesn't remove the item unless you push yes..

async void OnDeleteBook(object sender, EventArgs e)
{
    var book = (sender as MenuItem).CommandParameter as BooksIWant;

    if (await DisplayAlert("Warning", $"Are you sure you want to delete {book.Author} {book.BookTitle}?", "Yes", "No"))
        await _connection.DeleteAsync(book);
    _booksIWant.Remove(book);
}
2

There are 2 best solutions below

1
On BEST ANSWER

You need to use {} to create a block of statements. Without them, only the statement immediately after the IF is executed;

if (await DisplayAlert("Warning", $"Are you sure you want to delete {book.Author} {book.BookTitle}?", "Yes", "No"))
{
  await _connection.DeleteAsync(book);
  _booksIWant.Remove(book);
}

This is basic C#, not anything specific to Xamarin.

0
On

You should code like below

async void OnDeleteBook(object sender, EventArgs e){
var book = (sender as MenuItem).CommandParameter as BooksIWant;

if (await DisplayAlert("Warning", $"Are you sure you want to delete {book.Author} {book.BookTitle}?", "Yes", "No")){
    await _connection.DeleteAsync(book);
_booksIWant.Remove(book);}}

Delete and Remove method call needs to be inside the if loop