2017-08-11 126 views
1

如何刪除ListView中的選定項目,ListView項目來自SQLite.net數據庫 下面是我的代碼,但是當我刪除所有行並向db添加新項目時,我無法從列表視圖如何刪除ListView中的選定項目android xamarin

private void popmenu(object sender, AdapterView.ItemClickEventArgs e) 
    { 
     var menu = new PopupMenu(this, listnames.GetChildAt(e.Position)); 
     menu.Inflate(Resource.Layout.popup_menu); 
     menu.MenuItemClick += (s, A) => 
     { 
      switch (A.Item.ItemId) 
      { 
       case Resource.Id.pop_button1: 
        // update stuff 
        string dpPath = Path.Combine(System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal), "user.db3"); 
        db = new SQLiteConnection(dpPath); 
        var data = db.Table<LoginTable>(); 
        // Toast.MakeText(this, "row:" + (e.Position+1), ToastLength.Short).Show(); 
        int ww =(e.Position + 1); 
        var data1 = data.Where(x => x.id == ww); 
        foreach (var item in data1) 
        { 
         db.Delete(item); 

         Toast.MakeText(this, "Delete Successfully", ToastLength.Short).Show(); 
        } 

         break; 

      } 
     }; 

回答

0

刪除一行,您可以在適配器的代碼添加刪除項功能,例如:

public class MainAdapter : BaseAdapter<string> 
{ 

    private List<string> items = new List<string>(); 
    private Activity context; 

    public MainAdapter(Activity context, List<string> items) : base() 
    { 
     this.context = context; 
     this.items = items; 
    } 

    ... 

    public void RemoveItemAt(int position) 
    { 
     items.RemoveAt(position); 
    } 

} 
在產品Click事件

然後:

private void MListView_ItemClick(object sender, AdapterView.ItemClickEventArgs e) 
{ 
    adapter.RemoveItemAt(e.Position); 
    adapter.NotifyDataSetChanged(); 
} 

enter image description here

+0

那麼如何從數據庫中刪除? – hamid

+0

@hamid,如果你的行ID與列表項目的順序相同,那麼你可以使用'e.position'作爲id從你的db中刪除這個項目,也許你可以查看這個博客:[從在Xamarin Android中使用C#的SQLite DB](http://slackshotindustries.blogspot.sg/2013/06/deleting-from-db-using-sqlite-in-android.html)。 –

相關問題