Home > Mobile >  Xamarin/SQLite/C# - How to delete a row from listview and SQLite table with menu item delete
Xamarin/SQLite/C# - How to delete a row from listview and SQLite table with menu item delete

Time:10-13

Problem: So this is not an uncommon question on coding forums but there seems to be a variety of ways in which people apply delete buttons and after days of attempts I'm asking for some advice regarding my method.

I have a simple app that takes some user input and uses it to to calculate holiday leave days. I have a simple SQLite db set up like so to handle new entries:

public class LeaveEntry
{
    [PrimaryKey, AutoIncrement]
    public int ID { get; set; }
    public string Date { get; set; }
    public string Hours { get; set; }
    public string Days { get; set; }
}

I then set up the DB connection in this class and create some save and delete methods:

public class Database
{
    readonly SQLiteAsyncConnection _database;

    public Database (string dbPath)
    {
        _database = new SQLiteAsyncConnection(dbPath);
        _database.CreateTableAsync<LeaveEntry>().Wait();
    }

    public Task<List<LeaveEntry>> GetLeaveEntryAsync()
    {
        return _database.Table<LeaveEntry>().ToListAsync();
    }

    public Task<int> SaveLeaveEntry(LeaveEntry leaveEntry)
    {
        return _database.InsertAsync(leaveEntry);
    }

    public Task<int> DeleteLeaveEntry(LeaveEntry leaveEntry)
    {
        return _database.DeleteAsync(leaveEntry);
    }
}

Using the SaveLeaveEntry method I can successfuly add leave entries to a listview on another page but I'm having trouble deleting them. On this listview page I have added a menu item with a delete button when the user holds the listview item. When they select the delete menu item, I currently have it set to do this:

public void MenuItem_Clicked(object sender, EventArgs e)
    {
        LeaveEntry itemToDelete = ((sender as MenuItem).BindingContext as LeaveEntry);

        // Unfinished code attempt
        await App.Database.DeleteLeaveEntry(new LeaveEntry
        {
            ID = listView.SelectedItem.
        });
    }

In my mind, I am trying to use the selected item reference to pull that item from the db but it is simply doing nothing. I know I am missing something simple here but am getting a little burned out on the issue. Any help is appreciated. Can provide further code or info if required.

CodePudding user response:

In my mind, I am trying to use the selected item reference to pull that item from the db but it is simply doing nothing.

You should use the current holded item as the parameter of method DeleteLeaveEntry instead of creating a new item.

Please try the following code:

 LeaveEntry itemToDelete = ((sender as MenuItem).BindingContext as LeaveEntry);
 App.Database.DeleteLeaveEntry(itemToDelete);

Note:

In addition,if you don't trigger event ItemSelected of your listview,the value of listView.SelectedItem will be null.

  • Related