CRUD Operations In Xamarin.Forms

Introduction

In this article, we are going to learn CRUD operations in Xamarin.Forms using SQLite. So, starting with implementation, first we will discuss SQLite.

Defining SQLite

SQLite is a light weight transaction database with zero configuration which is built for all three platforms that we are targeting in Xamarin.forms application.

Setting up SQLite

First, we need to setup SQLite for development. To set SQLite three main steps are needed which are:

  • Install sqlite-net-pcl from NuGet package manager for solution.
  • Declare Interface in PCL
  • Implement interface in all projects.

These steps are explained in detail in the article named - Setting Up SQLite In Xamarin.Forms

You have to complete setting up SQLite for your project. Then, move towards CRUD operations.

CRUD Operations

In this example, we are going to make a UI of Notes. Here, you can save notes and their description in your application. And, you can also read, update, and delete these.

  • Creating and reading a data
    Let’s make user interface for our application, in which we create data, and then read it.

XAML

  1. <StackLayout>  
  2.       <Label Text="Save Your Notes:"></Label>  
  3.       <Entry Placeholder="Enter Notes Title" x:Name="Title"></Entry>  
  4.       <Entry Placeholder="Enter Notes Description" x:Name="Description"></Entry>  
  5.       <Button Text="ADD NOTE" Clicked="OnAdd"></Button>  
  6.   
  7.       <Label Text="Saved Notes" VerticalOptions="End"></Label>  
  8.       <ListView VerticalOptions="EndAndExpand" x:Name="mylistview">  
  9.           <ListView.ItemTemplate>  
  10.               <DataTemplate>  
  11.                   <TextCell Text="{Binding Title}" Detail="{Binding Desc}">  
  12.                   </TextCell>  
  13.               </DataTemplate>  
  14.           </ListView.ItemTemplate>  
  15.       </ListView>  
  16.   </StackLayout>  

Output

Output
Now, make a test class in which we will save our data.

Test Class 

  1. public class test  
  2.     {  
  3.         [PrimaryKey, AutoIncrement]  
  4.         public int id { get; set; }  
  5.   
  6.         [MaxLength(255)]  
  7.         public string Title { get; set; }  
  8.   
  9.         [MaxLength(1000)]  
  10.         public string Desc { get; set; }  
  11.     }   

And make some code to save data in our application. And when data is saved, it is shown in the list view which is already made in the UI of our application.

Code

  1. private SQLiteAsyncConnection _connection;  
  2.         private ObservableCollection<test> _test;  
  3.   
  4.         public SQLiteDbTest()  
  5.         {  
  6.             InitializeComponent();  
  7.             _connection = DependencyService.Get<ISQLiteDb>().GetConnection();  
  8.   
  9.         }  
  10.   
  11.         protected async override void OnAppearing()  
  12.         {  
  13.            await _connection.CreateTableAsync<test>();  
  14.             var abc = await _connection.Table<test>().ToListAsync();  
  15.             _test = new ObservableCollection<test>(abc);  
  16.             mylistview.ItemsSource = _test;  
  17.   
  18.             base.OnAppearing();  
  19.         }  
  20.   
  21.         void OnAdd(object sender, System.EventArgs e)  
  22.         {  
  23.             var test = new test { Title = Title.Text, Desc = Description.Text };  
  24.             _connection.InsertAsync(test);  
  25.             _test.Add(test);  
  26.   
  27.         }  

Two main methods are used in this code.

Firstly, we override OnAppearing method. In this method we make a table of name test which is generated from our test class. And if some data is present in this table then it is converted into a list this list is assigned to the observable collection and sets the item source of our list to the observable collection we made at the top.

And the second method calls when user clicks on Add Note button. In this method, values are saved in db and also in our observable collection.

Now, add some data.

Output

Output
Now click on ADD NOTE button.

Output

Output
Here you see that our first note is added and shown in list view. This is how we can create and read data in our application. Now move towards updating and deleting a data.

  • Update and delete data
    Now add two more buttons of delete and update.

Xaml

  1. <StackLayout>  
  2.     <StackLayout Orientation="Horizontal">  
  3.         <Button Clicked="OnDelete" Text="Delete"></Button>  
  4.         <Button Clicked="OnUpdate" Text="Update"></Button>  
  5.     </StackLayout>  
  6.       
  7.     <Label Text="Save Your Notes:"></Label>  
  8.     <Entry Placeholder="Enter Notes Title" x:Name="Title"></Entry>  
  9.     <Entry Placeholder="Enter Notes Description" x:Name="Description"></Entry>  
  10.     <Button Text="ADD NOTE" Clicked="OnAdd"></Button>  
  11.   
  12.     <Label Text="Saved Notes" VerticalOptions="End"></Label>  
  13.     <ListView VerticalOptions="EndAndExpand" x:Name="mylistview">  
  14.         <ListView.ItemTemplate>  
  15.             <DataTemplate>  
  16.                 <TextCell Text="{Binding Title}" Detail="{Binding Desc}">  
  17.                     <TextCell.ContextActions>  
  18.                         <MenuItem Text="Delete" CommandParameter="{Binding .}" IsDestructive="True" Clicked="OnDelete"></MenuItem>  
  19.                         <MenuItem Text="Update" CommandParameter="{Binding .}" IsDestructive="True" Clicked="OnUpdate"></MenuItem>  
  20.                     </TextCell.ContextActions>  
  21.                 </TextCell>  
  22.             </DataTemplate>  
  23.         </ListView.ItemTemplate>  
  24.     </ListView>  
  25. </StackLayout>  

Output

Output
Now code Delete and Update Events.

Code

  1. void OnDelete(object sender, System.EventArgs e)  
  2. {  
  3.     var del = _test[0];  
  4.     _connection.DeleteAsync(del);  
  5.     _test.Remove(del);  
  6.   
  7. }  
  8.   
  9. void OnUpdate(object sender, System.EventArgs e)  
  10. {  
  11.     var update = _test[0];  
  12.     update.Title += "Updated";  
  13.     _connection.UpdateAsync(update);  
  14.     OnAppearing();  
  15.   
  16. }  

Output

Output
Now Click on Update button. It will update the first value in our list.

Output

Output
Here, you will see that when we click on update button, the value is updated.

Now, click on Delete button.

Output

Output
And when we click on delete button, the first record is deleted.

This is a very small and simple example of CRUD operations. Happy Coding!!!