Hashir Malik
Hashir Malik

Reputation: 808

How to delete an Item selected form ListView in Xamarin

I'm building a Xamarin CrossPlatform App!

App contains 2 pages : HomePage, DetailGetData

HomePage: This page contains a ListView which is displaying list of data form webapi in cells and whenever I clicked each cell it goes to DetailGetDatapage which shows the detail of that data.

Problem: Now the problem is that I wanted to delete that selected item from DetailGetData page. A DeleteButton is placed and when i press that button that details and selected item should be deleted from the ListView as well. How it is possible ?

ScreenShot DetailGetData :https://i.sstatic.net/TXg4G.png

ScreenShot HomePage : https://i.sstatic.net/g1Hn1.png

Code:

DetailGetData Xaml:

 <?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             x:Class="Last_MSPL.Views.DetailGetData">

    <StackLayout HorizontalOptions="Center" VerticalOptions="Center">

        <Label Text="{Binding employee_name}" x:Name="empname" FontSize="Medium" FontAttributes="Bold" />
        <Label Text="{Binding employee_age}" x:Name="age" FontSize="Medium" FontAttributes="Bold" />
        <Label Text="{Binding employee_salary}" x:Name="salary" FontSize="Medium" FontAttributes="Bold" />

        <Button x:Name="DeleteItem" Text="Delete" Clicked="DeleteItem_Clicked"  />
    </StackLayout>

</ContentPage>

HomePage Xaml:

    <?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             x:Class="Last_MSPL.HomePage">


    <AbsoluteLayout HorizontalOptions="FillAndExpand" VerticalOptions="FillAndExpand">
        <ListView x:Name="Demolist" ItemSelected="OnItemSelected" BackgroundColor="White">
            <ListView.ItemTemplate>
                <DataTemplate>
                    <ViewCell Height="100">
                        <ViewCell.ContextActions>
                            <MenuItem x:Name="OnMore" Clicked="OnMore_Clicked" CommandParameter="{Binding .}"
                                 Text="More" />
                            <MenuItem x:Name="OnDelete" Clicked="OnDelete_Clicked" CommandParameter="{Binding .}"
                                 Text="Delete" IsDestructive="True" />
                        </ViewCell.ContextActions>
                        <StackLayout HorizontalOptions="FillAndExpand" VerticalOptions="FillAndExpand" Padding="30,0">

                            <Label Text="{Binding employee_name}" FontAttributes="bold" FontSize="Small" TextColor="Black" x:Name="en"/>
                            <Label Text="{Binding employee_age}" FontSize="Micro" TextColor="Black" FontAttributes="Italic"/>
                            <Label Text="{Binding id}" IsVisible="False" />


                        </StackLayout>
                    </ViewCell>
                </DataTemplate>
            </ListView.ItemTemplate>
        </ListView>

        <ImageButton Source="fedit.png" 
            BackgroundColor="Transparent"
            AbsoluteLayout.LayoutFlags="PositionProportional"  
            AbsoluteLayout.LayoutBounds=".95,.95,55,55" 
            Clicked="ImageButton_Clicked">
        </ImageButton>

    </AbsoluteLayout>
</ContentPage>

HomePage.cs:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net.Http;
using Newtonsoft.Json;
using Xamarin.Forms;
using Xamarin.Forms.Xaml;
using Last_MSPL.MenuItems;
using Last_MSPL.Views;
using System.Collections;

namespace Last_MSPL
{
    [XamlCompilation(XamlCompilationOptions.Compile)]
    public partial class HomePage : ContentPage
    {
        public IEnumerable ObjOrderList { get; private set; }


        public HomePage()
        {
            ((NavigationPage)Application.Current.MainPage).BarBackgroundColor = Color.Black;
            InitializeComponent();
            Get();
        }



        public async void Get()
        {
            HttpClient client = new HttpClient();
            try
            {
                var respone = await client.GetStringAsync("http://dummy.restapiexample.com/api/v1/employees");
                List<GetData> ObjOrderList = JsonConvert.DeserializeObject<List<GetData>>(respone);
                var totalCount = ObjOrderList.Count;
                Demolist.ItemsSource = ObjOrderList.GetRange(0, 40);
            }
            catch (Exception ex)
            {
                throw;
            }
        }


        public async void OnItemSelected(object sender, SelectedItemChangedEventArgs e)
        {
            HttpClient client = new HttpClient();
            if (Demolist.SelectedItem != null)
            {

                var respone = await client.GetStringAsync("http://dummy.restapiexample.com/api/v1/employees");
                List<GetData> ObjOrderList = JsonConvert.DeserializeObject<List<GetData>>(respone);
                var abc = (GetData)e.SelectedItem;

                GetData data = new GetData();
                data = ObjOrderList.ToList().Where(x => x.id == abc.id).FirstOrDefault();

                var detailPage = new DetailGetData(data);
                detailPage.BindingContext = e.SelectedItem as GetData;
                Demolist.SelectedItem = null;
                await Navigation.PushModalAsync(detailPage);

            }
        }

DetailGetData.cs:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net.Http;
using Newtonsoft.Json;
using Xamarin.Forms;
using Xamarin.Forms.Xaml;
using Last_MSPL.MenuItems;

namespace Last_MSPL.Views
{
    [XamlCompilation(XamlCompilationOptions.Compile)]
    public partial class DetailGetData : ContentPage
    {
        public DetailGetData(GetData _data)
        {
            InitializeComponent();
            BindingList(_data);

        }



        public void BindingList(GetData data)
        {
            empname.Text = data.employee_name;
            age.Text = data.employee_age;
            salary.Text = data.employee_salary;
        }


        public async void DeleteItem_Clicked(object sender, EventArgs e)
        {





            await Navigation.PopModalAsync();
        }
    }
}

Upvotes: 3

Views: 4509

Answers (2)

AbbyWang - MSFT
AbbyWang - MSFT

Reputation: 650

You can realize the function of deleting the item by adding a static datasouce class. And set the Demolist.ItemsSource = DataSource.collection; When click delete button in DetailGetData page, modify the Demolist.ItemsSource by deleting the item. So the code is like this:

DataSource.cs

using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Text;

namespace App10
{
    public static class DataSource
    {
        public static ObservableCollection<GetData> collection;

        static DataSource()
        {
        }
        public static void persist(List<GetData> collection)
        {
            //do something here
        }

        public static void initializeData(List<GetData> listdata)
        {
            collection = new ObservableCollection<GetData>(listdata);
        }
    }
}

MainPage.xaml.cs

[XamlCompilation(XamlCompilationOptions.Compile)]
    public partial class MainPage : ContentPage
    {
        List<GetData> dataList;
        public MainPage()
        {
            //((NavigationPage)Application.Current.MainPage).BarBackgroundColor = Color.Black;
            InitializeComponent();
            Get();
            //RefreshList();
        }
        public async void Get()
        {
            HttpClient client = new HttpClient();
            try
            {
                var respone = await client.GetStringAsync("http://dummy.restapiexample.com/api/v1/employees");
                List<GetData> ObjOrderList = JsonConvert.DeserializeObject<List<GetData>>(respone);
                var totalCount = ObjOrderList.Count;

                dataList = ObjOrderList.GetRange(0, 40);
                DataSource.initializeData(dataList);
                Demolist.ItemsSource = DataSource.collection;

            }
            catch (Exception ex)
            {
                throw;
            }
        }


        public async void OnItemSelected(object sender, SelectedItemChangedEventArgs e)
        {
            HttpClient client = new HttpClient();
            if (Demolist.SelectedItem != null)
            {

                var respone = await client.GetStringAsync("http://dummy.restapiexample.com/api/v1/employees");
                List<GetData> ObjOrderList = JsonConvert.DeserializeObject<List<GetData>>(respone);
                var abc = (GetData)e.SelectedItem;

                GetData data = new GetData();
                data = ObjOrderList.ToList().Where(x => x.id == abc.id).FirstOrDefault();

                var detailPage = new DetailGetData(data);
                detailPage.BindingContext = e.SelectedItem as GetData;
                Demolist.SelectedItem = null;
                await Navigation.PushModalAsync(detailPage);

            }
        }
}

DetailGetData.xaml.cs

   [XamlCompilation(XamlCompilationOptions.Compile)]
    public partial class DetailGetData : ContentPage
    {
        public GetData thisData;

        public DetailGetData(GetData _data)
        {
            InitializeComponent();
            BindingList(_data);
            thisData = _data;

        }


        public void BindingList(GetData data)
        {
            empname.Text = data.employee_name;
            age.Text = data.employee_age;
            salary.Text = data.employee_salary;
        }


        public async void DeleteItem_Clicked(object sender, EventArgs e)
        {

            GetData toberemoveditem = (from item in DataSource.collection
                                       where item.id == thisData.id
                             select item)
                            .FirstOrDefault<GetData>();
            DataSource.collection.Remove(toberemoveditem);


            await Navigation.PopModalAsync();
        }
    }

Upvotes: 3

Wasif Mahmood Mustafa
Wasif Mahmood Mustafa

Reputation: 597

Initialize your List in some class and make it static and use it in your Home Page. And then in your Detail Page in Delete event just write this code to remove the item from the list.

var remove = list.Where(x => x.employee_name == empname.Text).Single();
list.Remove(remove);

Change the code according to your model class. I hope it helps.

Upvotes: 2

Related Questions