1

I am using Xamarin.Forms.I want to remove the selected item in listview after clicking Remove button.

My xaml

 <ListView x:Name="ProductsListView"
          HasUnevenRows="True"
          BackgroundColor="#ecf0f1"
          SeparatorVisibility="None"
          HorizontalOptions="FillAndExpand"
          VerticalOptions="FillAndExpand">

                <ListView.ItemTemplate>
                    <DataTemplate>
                        <ViewCell>
                            <StackLayout Margin="6,4,6,4"
                             BackgroundColor="White">
                                <StackLayout Orientation="Horizontal">
                                    <Label Text="Item ID" Margin="25,10,4,4" FontSize="Small" TextColor="Black"  />
                                    <Label Text="{Binding retail_modified_item_id}"  Margin="25,10,4,4" TextColor="Black" FontSize="12" />
                                </StackLayout>

                                <StackLayout Orientation="Horizontal">
                                    <Label Text="Name" Margin="25,2,8,4" TextColor="Black" FontSize="Small" />
                                    <Label Text="{Binding name}" Margin="32,1,8,4" TextColor="Black" FontSize="Small" />
                                    <Switch IsToggled="false"  Margin="210,2,2,2" Toggled="Switch_Toggled" />
                                </StackLayout>

                                <StackLayout Orientation="Horizontal">
                                    <Label Text="OldPrice"  Margin="25,2,8,4" TextColor="Black" FontSize="Small"/>
                                    <Label Text="{Binding old_price}" Margin="32,1,8,4" TextColor="Black" FontSize="Small" />
                                </StackLayout>

                                <StackLayout Orientation="Horizontal">
                                    <Label Text="NewPrice" Margin="25,2,8,4" TextColor="Black" FontSize="Small" />
                                    <Label Text="{Binding new_price}" Margin="32,1,8,4" TextColor="Black" FontSize="Small" />
                                </StackLayout>

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

My cs code

private void reject(object sender, EventArgs args)
    {
        foreach (var v in ProductsListView.SelectedItems)
        {
           ProductsListView.ItemSelected.Remove(v);
        }
        DisplayAlert("Rejected","Request Rejected!!", "OK");
    }

I am getting this error:

listview does not contain a definition for selecteditem, ItemSelected

5
  • If your issue has been completed with answer below , you can mark as completed my answer.
    – Batuhan
    Mar 28, 2019 at 8:50
  • Can you please explain what exactly are you trying to do here?
    – FreakyAli
    Mar 28, 2019 at 9:27
  • @G.hakim i want to delete the selected data after clicking reject button.i attached the delete code in reject function.but it throws error " listview does not contain a definition for selecteditem , ItemSelected"
    – Anu Priya
    Mar 28, 2019 at 9:30
  • Can you point out the line of code where this happens
    – FreakyAli
    Mar 28, 2019 at 9:32
  • foreach (var v in ProductsListView.SelectedItems) ProductsListView.ItemSelected.Remove(v); // selectedItem and itemSelected
    – Anu Priya
    Mar 28, 2019 at 9:34

2 Answers 2

2

You can try cast it to ProductListView,

var selectedItems = (ListView/* or ProductListView*/)sender; //-> you need casting to access it.

And you can change list view item source

public void reject(your_list_of_model_type your_list_of_model)
{
   your_list_of_model.RemoveRange(selectedItems);
   ProductListView.ItemSource = your_list_of_model;
}

Solution 2 :

Here is what you could do :

This be my model class :

public class Item  
{  
   public string ItemName { get; set; }  
   public string ItemDetails { get; set; }  
}  

And in my XAML or you can write this in code as well, bind to the Command Parameter of your Item template :

<Button Text="Delete" CommandParameter="{Binding ItemName}" Clicked="DeleteClicked"></Button>
Full Item Template will be like below :

<ListView.ItemTemplate>  
            <DataTemplate>  
               <ViewCell>  
                  <ViewCell.View>  
                     <StackLayout Orientation="Horizontal">  
                        <Label Text="{Binding ItemName}" HorizontalOptions="StartAndExpand" FontSize="30"></Label>  
                        <Button Text="Delete" CommandParameter="{Binding ItemName}" Clicked="DeleteClicked">        
                        </Button>  
                     </StackLayout>  
                  </ViewCell.View>  
               </ViewCell>  
            </DataTemplate>  
         </ListView.ItemTemplate>    

And in you code file you can do this :

public void DeleteClicked(object sender, EventArgs e)  
{  
   var item = (Xamarin.Forms.Button)sender;  
   Item listitem = (from itm in allItems 
                    where itm.ItemName == item.CommandParameter.ToString() 
                    select itm)
                   .FirstOrDefault<Item>();  
   allItems.Remove(listitem);  
}  

IMPORTANT : This would only delete the item from the bound collection. To delete it from the original list you need to use ObservableCollection

7
  • can you explain this code i can't understand.From this code how can i get all selected value ?
    – Anu Priya
    Mar 28, 2019 at 8:52
  • The type or namespace name 'ProductsListView' could not be found (are you missing a using directive or an assembly reference?) , The event 'ListView.ItemSelected' can only appear on the left hand side of += or -= i am getting these 2 errors
    – Anu Priya
    Mar 28, 2019 at 9:37
  • foreach statement cannot operate on variables of type 'ListView' because 'ListView' does not contain a public instance definition for 'GetEnumerator' - foreach (var item in selectedItems ) ERROR IN SELECTEDITEMS ..... The event 'ListView.ItemSelected' can only appear on the left hand side of += or -= ERROR IN ProductsListView.ItemSelected.Remove(item); Actually why these errors are happening what mistake i did ?
    – Anu Priya
    Mar 28, 2019 at 9:50
  • updated again my answer , you need get selected items and remove them your source and you can give updated source to ListView.ItemSource it will be changes.
    – Batuhan
    Mar 28, 2019 at 9:57
  • private void reject(object sender, EventArgs args) // Is args is your_list_of_model? what is your_list_of_model_type & your_list_of_model
    – Anu Priya
    Mar 28, 2019 at 10:01
0

You can add all the toggled items to a list, suppose selectedItems. And when you click REJECT button, delete the selectedItems from the datasource of listview.

The full code is like this:

MainPage.xaml:

<StackLayout Orientation="Vertical">
        <!-- Place new controls here -->
        <Button Text="APPROVE" 
           HorizontalOptions="Center"
           VerticalOptions="CenterAndExpand" />
        <Button Text="REJECT" 
           HorizontalOptions="Center"
           VerticalOptions="CenterAndExpand"
                Clicked="reject"/>
        <ListView x:Name="ProductsListView" 
          HasUnevenRows="True"
          BackgroundColor="#ecf0f1"
          SeparatorVisibility="None"
          HorizontalOptions="FillAndExpand"
          VerticalOptions="FillAndExpand">

            <ListView.ItemTemplate>
                <DataTemplate>
                    <ViewCell>
                        <StackLayout Orientation="Vertical" Margin="6,4,6,4"
                             BackgroundColor="White">

                            <StackLayout Orientation="Horizontal">
                                <Label Text="{Binding name}" Margin="32,1,8,4" TextColor="Black" FontSize="Small" />
                                <Switch IsToggled="false"  Margin="210,2,2,2" Toggled="Switch_Toggled" />
                            </StackLayout>

                            <StackLayout Orientation="Horizontal">
                                <Label Text="{Binding retail_modified_item_id}"  Margin="25,10,4,4" TextColor="Black" FontSize="12" />
                            </StackLayout>

                            <StackLayout Orientation="Horizontal">
                                <Label Text="OldPrice"  Margin="25,2,8,4" TextColor="Black" FontSize="Small"/>
                                <Label Text="{Binding old_price}" Margin="32,1,8,4" TextColor="Black" FontSize="Small" />
                            </StackLayout>

                            <StackLayout Orientation="Horizontal">
                                <Label Text="NewPrice" Margin="25,2,8,4" TextColor="Black" FontSize="Small" />
                                <Label Text="{Binding new_price}" Margin="32,1,8,4" TextColor="Black" FontSize="Small" />
                            </StackLayout>

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

MainPage.xaml.cs:

public partial class MainPage : ContentPage
    {
        ObservableCollection<ItemModel> allItems = new ObservableCollection<ItemModel>();
        List<ItemModel> selectedItems = new List<ItemModel>();

        public MainPage()
        {
            InitializeComponent();
            InitializeData();
            ProductsListView.ItemsSource = allItems;
        }

        private void reject(object sender, EventArgs e)
        {
            foreach (var v in selectedItems)
            {
                allItems.Remove(v);
            }
            DisplayAlert("Rejected", "Request Rejected!!", "OK");
        }

        private void Switch_Toggled(object sender, ToggledEventArgs e)
        {
            var switch1 = (Switch)sender;
            var item = (ItemModel)switch1.BindingContext;

            var isSelected = !item.selected;

            if (isSelected)
            {
                selectedItems.Add(item);
            }
            else
            {
                selectedItems.Remove(item);
            }
        }

        private void InitializeData() {
            allItems.Add(new ItemModel { name = "Onion Rings, Medium",
                retail_modified_item_id = 1000630,
                old_price = 1.29,
                new_price = 9.45,
                selected = false
            });

            allItems.Add(new ItemModel
            {
                name = "Hashbrowns",
                retail_modified_item_id = 1000739,
                old_price = 0.99,
                new_price = 8.5,
                selected = false
            });

            allItems.Add(new ItemModel
            {
                name = "Amstel Light, Single",
                retail_modified_item_id = 1002038,
                old_price = 3.5,
                new_price = 18,
                selected = false
            });

        }
    }

ItemModel.cs:

class ItemModel
    {
        public string name { get; set; }
        public int retail_modified_item_id { get; set; }
        public double old_price { get; set; }
        public double new_price { get; set; }
        public bool selected { get; set; }
    }
1
  • you must refresh the listview for see changes
    – Batuhan
    Mar 28, 2019 at 11:26

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.