Forum Xamarin Cross Platform with Xamarin

ListView Not updating after deleting item

Hello everyone. I am trying to delete listview item. The item it self deletes from the database fine but the list view doesn't update, I am even using an observableCollection. This is my code:

`public partial class MainPage : ContentPage
{
DatabaseCRUDOperations dcr = new DatabaseCRUDOperations();

    public MainPage()
    {
        InitializeComponent();

    }

    protected override void OnAppearing()
    {
        listUsers.ItemsSource = dcr.GetUsers();
    }


    private void Delete_Clicked(object sender, EventArgs e)
    {
        var user = (sender as MenuItem).CommandParameter as UserModel;
        dcr.DeleteMember(user.ID);
    }

    private void Handle_Clicked(object sender, EventArgs e)
    {
        Navigation.PushAsync(new UserRegistrationView());
    }
}`

This is the Xaml file for mainpage:

` <ContentPage.ToolbarItems>

</ContentPage.ToolbarItems>
<ContentPage.Content>

<ListView.ItemTemplate>


<TextCell.ContextActions>

</TextCell.ContextActions>

            </DataTemplate>
        </ListView.ItemTemplate>
    </ListView>
</ContentPage.Content>`

`public class DatabaseCRUDOperations
{
//the connection
private static SQLiteConnection _connection;

    //Create database
    public DatabaseCRUDOperations()
    {
        //get the connection for independent platform
        _connection = DependencyService.Get<SQLiteDb>().GetConnection();

        //create table in database
        _connection.CreateTable<UserModel>();


    }

    //Get the users from the database
    public ObservableCollection<UserModel> GetUsers()
    {
      //  IEnumerable<UserModel> user = _connection.Table<UserModel>().ToList();
        ObservableCollection<UserModel> user = new ObservableCollection<UserModel>(_connection.Table<UserModel>().ToList());
        return user;
    }

    //Add member to the database
    public string AddMember(UserModel _user)
    {
        //Access the DB and add the user
        _connection.Insert(_user);
        return "Successfully added member!";
    }

    //Delete user from the database
    public string DeleteMember(int id)
    {
        //Access the DB and delete the user at this ID
        _connection.Delete<UserModel>(id);

        return "Successfully deleted member!";
    }

}`

` [Table("UserModel")]
public class UserModel
{
[PrimaryKey, AutoIncrement]
public int ID { get; set; }

    public string FirstName { get; set; }

    public string LastName { get; set; }

}`

public interface SQLiteDb { SQLiteConnection GetConnection(); }

` public partial class UserRegistrationView : ContentPage, INotifyPropertyChanged
{
public DatabaseCRUDOperations userDatabase;
public UserModel user;

    public UserRegistrationView ()
    {
        InitializeComponent ();
    }

    public void Save_Clicked(object o, EventArgs e)
    {
        user = new UserModel
        {
            FirstName = fname.Text,
            LastName = lname.Text
        };

        userDatabase = new DatabaseCRUDOperations();
        userDatabase.AddMember(user);


    }

}`

Answers

  • kentuckerkentucker USMember ✭✭✭✭✭

    I do see where you remove the item from the database. I do not see where you remove the item from the observablecollection that the ListView is bound to.

  • TheXamDevTheXamDev Member
    edited February 2018

    Hi Ken, I am having problems doing that, I can't convert a list to an observableCollection I just get an error. I updated my code, I have an error on this line " items = _connection.Table().ToList();" it says "Cannot implicitly convert type 'System.Collections.Generic.List<MVVM.Model.User>' to 'System.Collections.ObjectModel.ObservableCollection<MVVM.Model.User>' Don't know how to fix it:

    This is the new code:

    `using MVVM.Model;
    using SQLite;
    using System;
    using System.Collections.Generic;
    using System.Collections.ObjectModel;
    using System.Linq;
    using System.Text;
    using Xamarin.Forms;

    namespace MVVM.SQL
    {
    public class DataAccess
    {
    static SQLiteConnection _connection;
    private static int count = 0;
    ObservableCollection items;

        public DataAccess()
        {
            count++;
    
            _connection = DependencyService.Get<ISQLiteDb>().GetConnection();
    
            _connection.CreateTable<User>();
    
            if (count == 1)
            {
                ObservableCollection<User> users = new ObservableCollection<User>
                {
                    new User { FirstName = "John", LastName = "Smith"},
                    new User { FirstName = "Joe", LastName = "bean"},
                    new User { FirstName = "George", LastName = "jay"},
                    new User { FirstName = "Xamarin", LastName = "Forms"}
                };
    
                if(_connection.Table<User>().Count() != 10)
                {
                    _connection.InsertAll(users);
                }
    
            }
    
            items = _connection.Table<User>().ToList();
        }
    
        public ObservableCollection<User> GetAllUsers()
        {
            return items;
        }
    
        public IEnumerable<User> GetAllUsers(string searchText = null)
        {
            return items.Where(n => n.FirstName.StartsWith(searchText, StringComparison.CurrentCultureIgnoreCase));
        }
    
        public void DeleteUser(User user)
        {
            _connection.Delete(user);
    
            var temp2 = _connection.Table<User>().Count();
        }
    }
    

    }
    `

  • Update : I ended up solving it like this : public ObservableCollection Convert(IEnumerable original)
    {
    return new ObservableCollection(original);
    }

    but is this a good solution?

  • kentuckerkentucker USMember ✭✭✭✭✭

    I usually just loop through the list and add the items to the observable collection one at a time

Sign In or Register to comment.