After deleting a row , it just do not vanishes from the screen

别来无恙 提交于 2019-12-11 09:42:52

问题


I am developing an windows phone app using sqlite database.I am able to show out the database and delete the particular row I want to delete.But the problem is after I select the row and click delete the row does not vanishes at that time.I have to renter that page to see that it is deleted. Below here is the code of the class where I use the click_delete event

 public partial class History : PhoneApplicationPage
{
    ObservableCollection<historyTableSQlite> DB_HistoryList = new ObservableCollection<historyTableSQlite>();
    DbHelper Db_helper = new DbHelper();
    //public static int Selected_HistoryId;
    //int Selected_HistoryId;
    public static int Selected_HistoryId {get; set;}



    // string dbPath = Path.Combine(Windows.Storage.ApplicationData.Current.LocalFolder.Path, "db.sqlite");

    public History()
    {

        InitializeComponent();


    }

    protected override void OnNavigatedTo(NavigationEventArgs e)
    {

        Db_helper.AddInfo();
        ReadHistoryList_Loaded();
        // Selected_HistoryId = int.Parse(NavigationContext.QueryString["SelectedHistoryID"]);
    }

    public void ReadHistoryList_Loaded()
    {
        ReadAllContactsList dbhistory = new ReadAllContactsList();
        DB_HistoryList = dbhistory.GetAllHistory();//Get all DB contacts
        ListData.ItemsSource = DB_HistoryList.OrderByDescending(i => i.Id).ToList();


        //Latest contact ID can Display first

    }

    public void ListData_SelectionChanged(object sender, SelectionChangedEventArgs e)
    {
        if (ListData.SelectedIndex != -1)
        {
            historyTableSQlite listitem = ListData.SelectedItem as historyTableSQlite;
            History.Selected_HistoryId = listitem.Id;
        }
    }

    private void Delete_Click(object sender, EventArgs e)
    {
        Db_helper.DeleteContact(History.Selected_HistoryId);
        NavigationService.Navigate(new Uri("/History.xaml", UriKind.Relative));

    }

    private void DeleteAll_Click(object sender, EventArgs e)
    {
        DbHelper Db_helper = new DbHelper();
        Db_helper.DeleteAllContact();//delete all DB contacts
        DB_HistoryList.Clear();//Clear collections
        ListData.ItemsSource = DB_HistoryList;
    }



}
}

below is the class with all main functions

 public class DbHelper
{


    SQLiteConnection dbConn;


    public async Task<bool> onCreate(string DB_PATH)
    {
        try
        {
            if (!CheckFileExists(DB_PATH).Result)
            {
                using (dbConn = new SQLiteConnection(DB_PATH))
                {
                    dbConn.CreateTable<historyTableSQlite>();
                }
            }
            return true;
        }
        catch
        {
            return false;
        }
    }


    private async Task<bool> CheckFileExists(string fileName)
    {
        try
        {
            var store = await Windows.Storage.ApplicationData.Current.LocalFolder.GetFileAsync(fileName);
            return true;
        }
        catch
        {
            return false;
        }
    }

    //retrieve all list from the database
    public ObservableCollection<historyTableSQlite> ReadHistory()
    {
        using (var dbConn = new SQLiteConnection(App.DB_PATH))
        {
            List<historyTableSQlite> myCollection = dbConn.Table<historyTableSQlite>().ToList<historyTableSQlite>();
            ObservableCollection<historyTableSQlite> HistoryList = new ObservableCollection<historyTableSQlite>(myCollection);
            return HistoryList;
        }
    }

    // Insert the new info in the histrorytablesqlite table. 
    public void Insert(historyTableSQlite newcontact)
    {
        using (var dbConn = new SQLiteConnection(App.DB_PATH))
        {
            dbConn.RunInTransaction(() =>
            {
                dbConn.Insert(newcontact);
            });
        }
    }

    public void AddInfo()
    {


            DbHelper Db_helper = new DbHelper();
            Db_helper.Insert((new historyTableSQlite
            {
                Date = DateTime.Now.ToShortDateString(),
                Time = DateTime.Now.ToShortTimeString(),
                Zone = Checkin.Zone_st,
                Floor = Checkin.Floor_st,
                latitude = Checkin.Latitud_do,
                longtitude = Checkin.Longtitude_do
            }));

        }



    // Delete specific contact
    public void DeleteContact(int Id)
    {
        using (var dbConn = new SQLiteConnection(App.DB_PATH))
        {
            var existingvalue = dbConn.Query<historyTableSQlite>("select * from historyTableSQlite where Id =" + Id).FirstOrDefault();
            if (existingvalue != null)
            {
                dbConn.RunInTransaction(() =>
                {
                    dbConn.Delete(existingvalue);
                });
            }
        }
    }

    //Delete all contactlist or delete Contacts table
    public void DeleteAllContact()
    {
        using (var dbConn = new SQLiteConnection(App.DB_PATH))
        {
            //dbConn.RunInTransaction(() =>
            //   {
            dbConn.DropTable<historyTableSQlite>();
            dbConn.CreateTable<historyTableSQlite>();
            dbConn.Dispose();
            dbConn.Close();
            //});
        }
    }

below is the class with all tables

public class historyTableSQlite : INotifyPropertyChanged
{
    [SQLite.PrimaryKey, SQLite.AutoIncrement]

    public int Id
    {
        get;
        set;
    }
    private int idValue;

    private string dateValue = string.Empty;

    public string Date
    {
        get { return this.dateValue; }
        set
        {
            if (value != this.dateValue)
            {
                this.dateValue = value;
                NotifyPropertyChanged("Date");
            }
        }
    }


    private string timeValue = string.Empty;
    public string Time
    {
        get { return this.timeValue; }
        set
        {
            if (value != this.timeValue)
            {
                this.timeValue = value;
                NotifyPropertyChanged("Time");
            }
        }
    }

    private string floorValue = string.Empty;
    public string Floor
    {
        get { return this.floorValue; }
        set
        {
            if (value != this.floorValue)
            {
                this.floorValue = value;
                NotifyPropertyChanged("Floor");
            }
        }
    }

    public string zoneValue;
    public string Zone
    {
        get { return this.zoneValue; }
        set
        {
            if (value != this.zoneValue)
            {
                this.zoneValue = value;
                NotifyPropertyChanged("Zone");
            }
        }
    }

    private double latValue;
    public double latitude
    {
        get { return latValue; }
        set
        {
            if (value != this.latValue)
            {
                this.latValue = value;
                NotifyPropertyChanged("Latitude");
            }
        }
    }

    private double lonValue;
    public double longtitude
    {
        get { return this.lonValue; }
        set
        {
            if (value != this.lonValue)
            {
                this.lonValue = value;
                NotifyPropertyChanged("Longitude");
            }
        }
    }

    // public string isMarkPoint { get; set; }

    public historyTableSQlite()
    {

    }

    public historyTableSQlite(string date, string time, string floor, string zone, double lat, double lng)
    {
        Date = date;
        Time = time;
        Floor = floor;
        Zone = zone;
        latitude = lat;
        longtitude = lng;
    }
    public event PropertyChangedEventHandler PropertyChanged;

    private void NotifyPropertyChanged(String info)
    {
        if (PropertyChanged != null)
        {
            PropertyChanged(this, new PropertyChangedEventArgs(info));
        }
    }
}

回答1:


If you delete the item from your ObservableCollection, it will notify the ListBox to update its container.

In your code you have

// this is correct
ObservableCollection<historyTableSQlite> DB_HistoryList = new ObservableCollection<historyTableSQlite>();

But your problem is that you don't actually link your ListBox to it.

In your code you create a copy (and the worst kind of copy given what you're trying to do) and you set the ListBox ItemsSource to it. See below (you have this)

ListData.ItemsSource = DB_HistoryList.OrderByDescending(i => i.Id).ToList();

So basically, your ListBox is not an ObservableCollection but it's a List structure.

Deleting and Inserting into the List will not update the ListBox's UI.

Get rid of this List, find another way to sort your ObservableCollection.

Then you can basically do this

ListData.ItemsSource = DB_HistoryList;  // set the listbox to the actual obs collection

DB_HistoryList.RemoveAt(i);             // remove the item at index i
DB_HistoryList.RemoveItem(object);      // remove the object that matches


来源:https://stackoverflow.com/questions/26756460/after-deleting-a-row-it-just-do-not-vanishes-from-the-screen

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!