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
- <StackLayout>
- <Label Text="Save Your Notes:"></Label>
- <Entry Placeholder="Enter Notes Title" x:Name="Title"></Entry>
- <Entry Placeholder="Enter Notes Description" x:Name="Description"></Entry>
- <Button Text="ADD NOTE" Clicked="OnAdd"></Button>
-
- <Label Text="Saved Notes" VerticalOptions="End"></Label>
- <ListView VerticalOptions="EndAndExpand" x:Name="mylistview">
- <ListView.ItemTemplate>
- <DataTemplate>
- <TextCell Text="{Binding Title}" Detail="{Binding Desc}">
- </TextCell>
- </DataTemplate>
- </ListView.ItemTemplate>
- </ListView>
- </StackLayout>
Output
Now, make a test class in which we will save our data.
Test Class
- public class test
- {
- [PrimaryKey, AutoIncrement]
- public int id { get; set; }
-
- [MaxLength(255)]
- public string Title { get; set; }
-
- [MaxLength(1000)]
- public string Desc { get; set; }
- }
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
- private SQLiteAsyncConnection _connection;
- private ObservableCollection<test> _test;
-
- public SQLiteDbTest()
- {
- InitializeComponent();
- _connection = DependencyService.Get<ISQLiteDb>().GetConnection();
-
- }
-
- protected async override void OnAppearing()
- {
- await _connection.CreateTableAsync<test>();
- var abc = await _connection.Table<test>().ToListAsync();
- _test = new ObservableCollection<test>(abc);
- mylistview.ItemsSource = _test;
-
- base.OnAppearing();
- }
-
- void OnAdd(object sender, System.EventArgs e)
- {
- var test = new test { Title = Title.Text, Desc = Description.Text };
- _connection.InsertAsync(test);
- _test.Add(test);
-
- }
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
Now click on ADD NOTE button.
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
- <StackLayout>
- <StackLayout Orientation="Horizontal">
- <Button Clicked="OnDelete" Text="Delete"></Button>
- <Button Clicked="OnUpdate" Text="Update"></Button>
- </StackLayout>
-
- <Label Text="Save Your Notes:"></Label>
- <Entry Placeholder="Enter Notes Title" x:Name="Title"></Entry>
- <Entry Placeholder="Enter Notes Description" x:Name="Description"></Entry>
- <Button Text="ADD NOTE" Clicked="OnAdd"></Button>
-
- <Label Text="Saved Notes" VerticalOptions="End"></Label>
- <ListView VerticalOptions="EndAndExpand" x:Name="mylistview">
- <ListView.ItemTemplate>
- <DataTemplate>
- <TextCell Text="{Binding Title}" Detail="{Binding Desc}">
- <TextCell.ContextActions>
- <MenuItem Text="Delete" CommandParameter="{Binding .}" IsDestructive="True" Clicked="OnDelete"></MenuItem>
- <MenuItem Text="Update" CommandParameter="{Binding .}" IsDestructive="True" Clicked="OnUpdate"></MenuItem>
- </TextCell.ContextActions>
- </TextCell>
- </DataTemplate>
- </ListView.ItemTemplate>
- </ListView>
- </StackLayout>
Output
Now code Delete and Update Events.
Code
- void OnDelete(object sender, System.EventArgs e)
- {
- var del = _test[0];
- _connection.DeleteAsync(del);
- _test.Remove(del);
-
- }
-
- void OnUpdate(object sender, System.EventArgs e)
- {
- var update = _test[0];
- update.Title += "Updated";
- _connection.UpdateAsync(update);
- OnAppearing();
-
- }
Output
Now Click on Update button. It will update the first value in our list.
Output
Here, you will see that when we click on update button, the value is updated.
Now, click on Delete button.
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!!!