Articles in this section
Category / Section

How to load the data from SQLite offline database in .NET MAUI ListView(SfListView)?

8 mins read

You can create a local database using SQLite and populate data for SfListView from the database in .NET MAUI.

Please follow the steps below to create a local database for SfListView,

Step 1: Install sqlite-net-pcl nuget package to the shared code project. You can refer to the SQLite documentation from here.

Step 2: Create database

Initialize SQLiteAsyncConnection and create a database table using the CreateTableAsync method. The ToListAsync returns the table data in the List format. The InsertAsync, DeleteAsync and UpdateAsync methods used to perform CRUD operations.

namespace ListViewMAUI
{
    public class SQLiteDatabase
    {
        readonly SQLiteAsyncConnection _database;
 
        public SQLiteDatabase(string dbPath)
        {
            _database = new SQLiteAsyncConnection(dbPath);
            _database.CreateTableAsync<Contacts>().Wait();
        }
 
        public Task<List<Contacts>> GetContactsAsync()
        {
            return _database.Table<Contacts>().ToListAsync();
        }
 
        public Task<int> AddContactAsync(Contacts item)
        {
            return _database.InsertAsync(item);
        }
 
        public Task<int> DeleteContactAsync(Contacts item)
        {
            return _database.DeleteAsync(item);
        }
 
        public Task<int> UpdateContactAsync(Contacts item)
        {
            return _database.UpdateAsync(item);
        }
    }
}

Step 3: Add SfListView in the ContentPage

<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             x:Class="ListViewMAUI.MainPage"
             xmlns:local="clr-namespace:ListViewMAUI"
             xmlns:syncfusion="clr-namespace:Syncfusion.Maui.ListView;assembly=Syncfusion.Maui.ListView">

    <ContentPage.ToolbarItems>
        <ToolbarItem Command="{Binding CreateContactsCommand}"
                     IconImageSource="add.png" />
    </ContentPage.ToolbarItems>

    <ContentPage.BindingContext>
        <local:ContactsViewModel x:Name="viewModel" />
    </ContentPage.BindingContext>

    <ContentPage.Content>
        <StackLayout>
            <syncfusion:SfListView x:Name="listView"
                                   ItemSize="60"
                                   ItemSpacing="5"
                                   TapCommand="{Binding EditContactsCommand}">
                <syncfusion:SfListView.ItemTemplate>
                    <DataTemplate>
                        ...
                    </DataTemplate>
                </syncfusion:SfListView.ItemTemplate>
            </syncfusion:SfListView>
        </StackLayout>
    </ContentPage.Content>

</ContentPage>

Step 4: Access data for ListView from database

Create database instance in the ViewModel and initialize the database.

namespace ListViewMAUI
{
    public class ContactsViewModel : INotifyPropertyChanged
    {
        private SQLiteDatabase database;
        private string path = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "contacts.db3");
 
        public SQLiteDatabase Database
        {
            get
            {
                if (database == null)
                    database = new SQLiteDatabase(path);
                return database;
            }
        }
    }
}

Get data from the database and assign it to the SfListView.ItemsSource property in the OnAppearing override method.

namespace ListViewMAUI
{
    public partial class MainPage : ContentPage
    {
        public MainPage()
        {
            InitializeComponent();
        }
 
        protected async override void OnAppearing()
        {   
            base.OnAppearing();
            listView.ItemsSource = await viewModel.Database.GetContactsAsync();
        }
    }
}

Step 5: Performing CRUD operations

In the command execution method, invoke the database asynchronous methods to perform operations.

 public class ContactsViewModel : INotifyPropertyChanged
 {
        public Contacts Item { get; set; }
        
        public Command CreateContactsCommand { get; set; }
        public Command<object> EditContactsCommand { get; set; }
        public Command SaveItemCommand { get; set; }
        public Command DeleteItemCommand { get; set; }
        public Command AddItemCommand { get; set; }
        
        public ContactsViewModel()
        {
            CreateContactsCommand = new Command(OnCreateContacts);
            EditContactsCommand = new Command<object>(OnEditContacts);
            SaveItemCommand = new Command(OnSaveItem);
            DeleteItemCommand = new Command(OnDeleteItem);
            AddItemCommand = new Command(OnAddNewItem);
        }
        
        private async void OnAddNewItem()
        {
            await this.Database!.AddContactAsync(Item!);
            await Shell.Current.Navigation.PopAsync();
        }
        
        private async void OnDeleteItem()
        {
            await this.Database!.DeleteContactAsync(Item!);
            await Shell.Current.Navigation.PopAsync();
        }
        
        private async void OnSaveItem()
        {
            await this.Database!.UpdateContactAsync(Item!);
            await Shell.Current.Navigation.PopAsync();
        }
        
        private void OnEditContacts(object obj)
        {
            Item = (Contacts)(obj as Syncfusion.Maui.ListView.ItemTappedEventArgs)!.DataItem;
            var editPage = new EditPage();
            editPage.BindingContext = this;
            Shell.Current.Navigation.PushAsync(editPage);
        }
        
        private void OnCreateContacts()
        {
            Item = new Contacts() { ContactName = "", ContactNumber = "" };
            var editPage = new EditPage();
            editPage.BindingContext = this;
            Shell.Current.Navigation.PushAsync(editPage);
        }
 }

Download the sample on GitHub.

Conclusion
I hope you enjoyed learning about how to load the data from SQLite offline database in SfListView.
You can refer to our .NET MAUI SfListView feature tour page to know about its other groundbreaking feature representations and documentation, and how to quickly get started for configuration specifications. You can also explore our .NET MAUI SfListView example to understand how to create and manipulate data.
For current customers, you can check out our components from the License and Downloads page. If you are new to Syncfusion, you can try our 30-day free trial to check out our other controls.
If you have any queries or require clarifications, please let us know in the comments section below. You can also contact us through our support forums, Direct-Trac, or feedback portal. We are always happy to assist you!

Did you find this information helpful?
Yes
No
Help us improve this page
Please provide feedback or comments
Comments (0)
Please  to leave a comment
Access denied
Access denied