Remove top item of ObservableCollection

Heinz Deubler 176 Reputation points
2023-02-06T00:22:23.4433333+00:00

I have a Maui.net MVVM app that pings a website every xx seconds and display the ping results in a listview (for demonstrations sake I removed the ping class and instead increment a counter).

After 5 pings I want the top ping result removed so that only the last 5 ping results show in the listview.

My question is: How can I remove the top item in the ObservableCollection .

oc.Remove(), oc.RemoveAt(0) and many other variations. I Usually get the following error:

"System.ArgumentOutOfRangeException: 'This collection cannot work with indices larger than Int32.MaxValue - 1 (0x7FFFFFFF - 1). (Parameter 'index')'"


<ContentPage xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             x:Class="xPing_Maui.Views.MainPage"
             BackgroundColor="LightGray" >
    <ContentPage.MenuBarItems>
        <MenuBarItem Text="File">
            <MenuFlyoutItem Text="Save"/>
            <MenuFlyoutItem  Text="Exit"/>
        </MenuBarItem>
        <MenuBarItem Text="Settings">
            <MenuFlyoutItem Text="Email Settings"/>
            <MenuFlyoutItem  Text="Ping Settings"/>
        </MenuBarItem>
    </ContentPage.MenuBarItems>
    <VerticalStackLayout>
        <ListView ItemsSource="{Binding ListV}" SelectionMode="Single"  Background="Gray"  SeparatorVisibility="None" Margin="20,20,20,20">
                       
        </ListView>
        <Grid>
            
        </Grid>
    </VerticalStackLayout>
</ContentPage>

Main Page code behind


using System.Diagnostics;
using xPing_Maui.ViewModels;

namespace xPing_Maui.Views;

public partial class MainPage : ContentPage
{
    
    public MainPage()
	{
		InitializeComponent();
         
        BindingContext = new VMMainPage();
    }
}





ViewModel


using Microsoft.VisualBasic.FileIO;
using PropertyChanged;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using xPing_Maui.Helper;
using xPing_Maui.Models;

namespace xPing_Maui.ViewModels
{
   

  //  [AddINotifyPropertyChangedInterface]
    public class LVMainPage
    {
        public ObservableCollection<string> ListV { get; set; }
        
        PingClass pg = new PingClass ();


        [Obsolete]
        public LVMainPage()
        {
            ListV = new ObservableCollection<string>();
            int Counter = 0;
            int cnt = 0;         
            
            Device.StartTimer(new TimeSpan(0, 0, 4), () =>
            {              
                ListV.Add(Counter.ToString());
                Counter++;   
              
                cnt++;
                if(cnt == 5)
                {
                    // Delete first row in the ObservableCollection
                    ListV.RemoveAt(0);
                    cnt = 0;                    
                }
               return true; 
            });
        }
    }
}

.NET
.NET
Microsoft Technologies based on the .NET software framework.
3,178 questions
.NET MAUI
.NET MAUI
A Microsoft open-source framework for building native device applications spanning mobile, tablet, and desktop.
2,597 questions
C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
9,964 questions
{count} votes

Accepted answer
  1. Viorel 110K Reputation points
    2023-02-11T07:12:23.24+00:00

    It seems to be a problem of MAUI. To work around, try removing the item before adding the new one, for example:

    Device.StartTimer( new TimeSpan( 0, 0, 4 ), ( ) =>
    {
        if( ListV.Count >= 5)
        {
            ListV.RemoveAt( 0 );
        }
    
        ListV.Add( Counter.ToString( ) );
        Counter++;
    
        return true;
    } );
    

    By the way, some of the classes and functions are obsolete.

    1 person found this answer helpful.

0 additional answers

Sort by: Most helpful