简体   繁体   中英

Deleting a selected item from a listview in xamarin (using a SQLite DB)

I want to delete a single selected row, I dont think my code is far off. Currently it deletes all rows in the listview thats saved on the SQLite DB which is great for a delete all button but I'm not wanting that. Below is my code:

 void SaveButton_Clicked(object sender, System.EventArgs e)
    {
        MainWindowViewModel APR = new MainWindowViewModel()
        {
            ProductName = proName.Text,
            TotalAPR = totAPR.Text,
            Total = tot.Text,
            Monthly = mon.Text
        };

            using (SQLiteConnection conn = new SQLiteConnection(App.FilePath))
        {
            conn.CreateTable<MainWindowViewModel>();
            int rowsAdded = conn.Insert(APR);
        }

        DisplayAlert("Saved!", "Your APR has been saved!", "OK");

        BindingContext = new MainWindowViewModel();

        OnAppearing();
    }


    void RemoveButton_Clicked(object sender, System.EventArgs e)
    {
        MainWindowViewModel APR = new MainWindowViewModel()
        {
            ProductName = proName.Text,
            TotalAPR = totAPR.Text,
            Total = tot.Text,
            Monthly = mon.Text
        };

        using (SQLiteConnection conn = new SQLiteConnection(App.FilePath))
        {
            conn.DeleteAll<MainWindowViewModel>();
            int rowsDeleted = conn.Delete(APR);
        }

        DisplayAlert("Deleted!", "This saved APR has been deleted!", "OK");

        BindingContext = new MainWindowViewModel();

        OnAppearing();
    }



    protected override void OnAppearing()
    {
        base.OnAppearing();
        using (SQLiteConnection conn = new SQLiteConnection(App.FilePath))
        {
            conn.CreateTable<MainWindowViewModel>();
            var APRS = conn.Table<MainWindowViewModel>().ToList();

            APRListView.ItemsSource = APRS;


        }
    }

I have also tried:

using (SQLiteConnection conn = new SQLiteConnection(App.FilePath))
        {
            conn.Delete<MainWindowViewModel>();
            int rowsDeleted = conn.Delete(APR);
        }

But I'm getting told to change it to conn.DeleteALL as per Intellisense.

// you do not need to create a new instance of your VM
var item = (MainWindowViewModel)APRListView.SelectedItem;

conn.Delete(item);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM