Performing CRUD Operations In Xamarin.Forms

In this article, we are going to learn about the CRUD (create, read, update, delete) operations in Xamarin.Forms. At the end of the article, you will be able to perform basic functionalities with the SQLite database.

Introduction

In this article, we are going to learn about the CRUD (create, read, update, delete) operations in Xamarin.Forms. At the end of the article, you will be able to perform the basic functionalities with the SQLite database.

Targeted Audience

People with basic knowledge of C# and Xamarin.

Tools

Visual Studio with Xamarin installed and with a SQLite connection set up.

CRUD operations are the four basic functions in the SQLite storage. Although, whatever the storage is, you have to perform these basic operations. Let’s see how to implement these operations in Xamarin.Forms using simple steps. Don’t forget, the SQLite connection must be built before performing these operations.

For learning purposes, I am going to create a contact list which contains the Name and Address of a person. Starting with creating a folder with the name “Models”, include a class in your Models folder with the name “Contacts”.

Performing CRUD Operations In Xamarin.Forms 

The class will become our table in the database with the same name. Create three properties - full Id, Name, and Address in the class. These will be our columns in the database. Remember to make Id the primary key. Use the following code.

C# Code
  1. using SQLite;  
  2. using System;  
  3. using System.Collections.Generic;  
  4. using System.Text;  
  5.   
  6. namespace PracApp1.Models  
  7. {  
  8.     public class Contacts  
  9.     {  
  10.         private int id;  
  11.         [PrimaryKey][AutoIncrement]  
  12.   
  13.         public int Id  
  14.         {  
  15.             get { return id; }  
  16.             set { id = value; }  
  17.         }  
  18.         private string name;  
  19.         public string Name  
  20.         {  
  21.             get { return name; }  
  22.             set { name = value; }  
  23.         }  
  24.         private string address;  
  25.         public string Address  
  26.         {  
  27.             get { return address; }  
  28.             set { address = value; }  
  29.         }          
  30.     }  
  31. }  

Now, let’s make the UI. Simply, create a stack layout and add two entries which will be used as Name and Address inputs. Also, add a "Save" button to save the data. Then, add a listview and give a name to it. This will be used to add reading or showing the data. Add a text cell in the DataTemplate tag with the properties of Text and Detail. Bind the text with “Name” and detail with the “Address” property, which are in the Contact List.

In the next step, create a Menu Item with a click event, ListItem_Delete. This will delete the selected item from the list. This is all we have to do for the UI. This will look like this.

Performing CRUD Operations In Xamarin.Forms 
 
XAML Code
  1. <?xml version="1.0" encoding="utf-8" ?>  
  2. <ContentPage xmlns="http://xamarin.com/schemas/2014/forms"  
  3.              xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"  
  4.              xmlns:local="clr-namespace:PracApp1"  
  5.              x:Class="PracApp1.MainPage"   
  6.              x:Name="ContentPage1">  
  7.     <StackLayout VerticalOptions="FillAndExpand" HorizontalOptions="FillAndExpand" Orientation="Vertical">  
  8.         <Entry x:Name="Name"></Entry>  
  9.         <Entry x:Name="Address"></Entry>  
  10.         <Button Text="Save" Clicked="Save"></Button>  
  11.         <ListView x:Name="ContactList" IsVisible="True">  
  12.             <ListView.ItemTemplate>  
  13.                 <DataTemplate>  
  14.                     <TextCell Detail="{Binding Address}" Text="{Binding Name}">  
  15.                         <TextCell.ContextActions>  
  16.                             <MenuItem Text="Delete Item" Clicked="ListItem_Delete" CommandParameter="{Binding .}">  
  17.                             </MenuItem>  
  18.                         </TextCell.ContextActions>  
  19.                     </TextCell>  
  20.                 </DataTemplate>  
  21.             </ListView.ItemTemplate>  
  22.         </ListView>  
  23.     </StackLayout>  
  24. </ContentPage>  

Create Operation

Now, in the .cs file, create a connection string. Using this connection, create the table of your Contacts list in the MainPage() function. Then, create an ObservableCollection list of your Contacts class, and in the "Save" event, insert async data from the input fields using their names.

Read Operation

For reading the data, make an object of your table in the database. And, set the item source of your UI list to this list of data.

C# Code
  1. using PracApp1.Models;  
  2. using System;  
  3. using System.Collections.Generic;  
  4. using System.Collections.ObjectModel;  
  5. using System.Linq;  
  6. using System.Text;  
  7. using System.Threading.Tasks;  
  8. using Xamarin.Forms;  
  9. using SQLite;  
  10. using PracApp1.Connections;  
  11.   
  12. namespace PracApp1  
  13. {  
  14.     public partial class MainPage : ContentPage  
  15.     {  
  16.   
  17.         SQLiteAsyncConnection conn = DependencyService.Get<ISqlConnection>().Connection();  
  18.   
  19.         public MainPage()  
  20.         {  
  21.             InitializeComponent();  
  22.             this.BindingContext = this;  
  23.   
  24.             conn.CreateTableAsync<Contacts>();  
  25.             ReadData();  
  26.               
  27.         }  
  28.   
  29.         private ObservableCollection<Contacts> cList;  
  30.   
  31.         public ObservableCollection<Contacts> CList  
  32.         {  
  33.             get { return cList; }  
  34.             set { cList = value; }  
  35.         }  
  36.   
  37.         private void Save(object sender, EventArgs e)  
  38.         {  
  39.             conn.InsertAsync(new Contacts() { Name = Name.Text, Address = Address.Text });  
  40.   
  41.             ReadData();  
  42.         }  
  43.   
  44.         public void ReadData()  
  45.         {  
  46.   
  47.             var list = conn.Table<Contacts>().ToListAsync().Result;  
  48.   
  49.             CList = new ObservableCollection<Contacts>(list);  
  50.             ContactList.ItemsSource = CList;  
  51.         }  
  52.         
  53.     }  
  54. }  

Now, you can add the data and also see it in a list like below.

Performing CRUD Operations In Xamarin.Forms 

Delete Operation

To delete the list item, go to your delete event and receive the sender as “mi” variable. The variable name can be anything you desire. Importantly, you have to specify the CommandParameter as your class item; otherwise, it will not be deleted because it will consider that as a whole Menu Item including other things. Call the ReadData function to update the list.

Performing CRUD Operations In Xamarin.Forms 
 
Performing CRUD Operations In Xamarin.Forms
 
C# Code
  1. private void ListItem_Delete(object sender, EventArgs e)  
  2.         {  
  3.             var mi = sender as MenuItem;  
  4.             var item = mi.CommandParameter as Contacts;  
  5.             conn.DeleteAsync(item);  
  6.             ReadData();  
  7.         }  

Update Operation

      The case is almost the same in "Update" as in the "Delete" operation. The difference is just the UpdateAsync function. For learning purposes, I am updating my list item with the static values. These values can be dynamic depending upon what you like.

      Performing CRUD Operations In Xamarin.Forms 
       
      Performing CRUD Operations In Xamarin.Forms 

      As you can see in the picture above, the record is updated successfully.

      C# Code
      1. private void Update(object sender, EventArgs e)  
      2.         {  
      3.             var mi = sender as MenuItem;  
      4.             var item = mi.CommandParameter as Contacts;  
      5.             item.Name= "Martin";  
      6.             item.Address = "New York";  
      7.             conn.UpdateAsync(item);  
      8.             ReadData();  
      9.         }  

      Summary

      Having better understanding with the CRUD operations helps you to generate a well-designed and controlled database. I hope this article gives you a way to do so in a proper manner.