Easily Load Appointments in WinUI Scheduler with SQLite and Perform CRUD Actions
Tags: winui, desktop, scheduler, sqlite
Published: 2024-02-19 03:07:44

---
title: Easily Load Appointments in WinUI Scheduler with SQLite and Perform CRUD Actions
published: true
date: 2024-02-13 09:30:00 UTC
tags: winui, desktop, scheduler, sqlite
canonical_url: https://www.syncfusion.com/blogs/post/winui-scheduler-sqlite-crud.aspx
cover_image: https://dev-to-uploads.s3.amazonaws.com/uploads/articles/kjvdyejryfsamd4ylzn0.png
---
In this blog, we’ll see how to load appointments in the WinUI Scheduler control from the SQLite database, execute CRUD (create, read, update, delete) actions, and dynamically update the Scheduler changes.

The Syncfusion [WinUI Scheduler](https://www.syncfusion.com/winui-controls/scheduler "Syncfusion WinUI Scheduler") has comprehensive scheduling capabilities, making it an excellent solution for appointment management tasks.

[SQLite](https://en.wikipedia.org/wiki/SQLite "SQLite"), renowned for its lightweight nature, open-source availability, and self-contained architecture. It is used for relational database management in embedded systems, mobile apps, and desktop software. Its simplicity and efficiency make it a popular choice among developers.

**Note:** Before proceeding, ensure you have familiarized yourself with the Getting Started with [WinUI Scheduler documentation](https://help.syncfusion.com/winui/scheduler/getting-started "Getting Started with WinUI Scheduler").

Create SQLite connection, define the model, and populate appointments

Let’s start by connecting the SQLite database with the Syncfusion WinUI Scheduler.

### Step 1: Install the required package

First, install the **sqlite-net-pcl** package to connect the SQLite database.

### ![sqlite net pcl NuGet package](https://www.syncfusion.com/blogs/wp-content/uploads/2024/02/sqlite-net-pcl-NuGet-package-1.png)Step 2: Create the SQLite connection

Define the SQLite connection using the dynamic **SQLiteConnection** API and set up the database path property in the  **SchedulerDatabase.cs**  file.

Refer to the following code example.

**SchedulerDatabase.cs**

```csharp
readonly SQLiteConnection sqLiteConnection;
public SchedulerDatabase(string dbPath)
{
    sqLiteConnection = new SQLiteConnection(dbPath);
}
```

Create an instance for the SQLite connection with the database **Path** property and initialize it in the **App.Xaml.cs** file to use the database.

**App.xaml.cs**

```csharp
static SchedulerDatabase database;
public static SchedulerDatabase Database
{
    get
    {
        if (database == null)
        {
            database = new SchedulerDatabase(System.IO.Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "WPFSchedulerDatabase.db3"));
        }
        return database;
    }
}
```

### Step 3: Define the database table model

Then, define the **Appointment** model class to hold the key property values extracted from the database table.

**Appointment.cs**

```csharp
public class Appointment
{
    [PrimaryKey, AutoIncrement, Unique]
    public int Id { get; set; }
    public string EventName { get; set; }
    public DateTime From { get; set; }
    public DateTime To { get; set; }
    public bool AllDay { get; set; }
    public string Notes { get; set; }
}
```

Create a table named  **Appointment**  in that SQLite database.

**SQLiteDatabase.cs**

```csharp
sqLiteConnection.CreateTable<Appointment>();
```

### Step 4: Populate SQLite database appointments

In the  **SchedulerViewModel**  class, populate the data from the SQLite database.

```csharp
public ObservableCollection<ScheduleAppointment> Appointments { get; set; }
var dataBaseAppointments = App.Database.GetSchedulerAppointments();
if (dataBaseAppointments != null && dataBaseAppointments.Count > 0)
{
    Foreach (Appointment appointment in dataBaseAppointments)
    {
        Appointments.Add(new ScheduleAppointment()
        {
            StartTime = appointment.From,
            EndTime = appointment.To,
            Subject = appointment.EventName,
            IsAllDay = appointment.AllDay,
            Id = appointment.Id
        });
    }
}
```

 Then, retrieve the appointments from the SQLite database in the **SchedulerDatabase.cs** file.

```csharp
public List<Appointment> GetSchedulerAppointments()
{
    return sqLiteConnection.Table<Appointment>().ToList();
}
```

### Step 5: Bind appointments to the Scheduler

Initialize the WinUI Scheduler control and bind its **ItemSource** property to the **Appointments** property of the **SchedulerViewModel** class.

Refer to the following code example.

**MainPage.xaml**

```xml
xmlns:scheduler="using:Syncfusion.UI.Xaml.Scheduler"
<Grid x:Name="grid">
    <Grid.DataContext>
        <local:SchedulerViewModel/>
    </Grid.DataContext>
    <scheduler:SfScheduler x:Name="Scheduler" ViewType="Week" AppointmentEdi-torClosing="Scheduler_AppointmentEditorClosing"
                     Al-lowedViewTypes="Day,Week,WorkWeek,Month,TimelineDay,TimelineWeek,TimelineWorkWeek,TimelineMonth"
                     ItemsSource="{Binding Appointments}">
    </scheduler:SfScheduler>
</Grid>
```

After executing the previous code examples, we’ll get output like in the following image.

<figure>

  <img src="https://www.syncfusion.com/blogs/wp-content/uploads/2024/02/Populating-appointments-from-SQLite-database-in-WinUI-Scheduler.png" alt="Populating appointments from SQLite database in WinUI Scheduler" style="width:100%">

  <figcaption>Populating appointments from SQLite database in WinUI Scheduler</figcaption>

</figure>

## Build a schedule appointment editor

Let’s create an appointment editor that enables the addition, saving, and deletion of appointments in the WinUI Scheduler.

When double-tapping the Scheduler, you will be able utilize the appointment editor to add, edit, and delete appointment details using the Scheduler **AppointmentEditorClosing** event.

```csharp
private void Scheduler_AppointmentEditorClosing(object sender, AppointmentEditor-ClosingEventArgs e)
{
    SchedulerViewModel viewModel = this.grid.DataContext as SchedulerViewModel;
    if (viewModel != null)
    {
        if (e.Action == AppointmentEditorAction.Add || e.Action == AppointmentE - ditorAction.Edit)
        {
            viewModel.AddAppointmentDetails(e.Action.ToString(), e.Appointment);
        }
        if (e.Action == AppointmentEditorAction.Delete && e.Appointment != null)
        {
            viewModel.DeleteSchedulerAppointment(e.Appointment);
        }
    }
}
```

Refer to the following image.

<figure>

  <img src="https://www.syncfusion.com/blogs/wp-content/uploads/2024/02/Appointment-editor-in-the-WinUI-Scheduler.png" alt="Appointment editor in the WinUI Scheduler" style="width:100%">

  <figcaption>Appointment editor in the WinUI Scheduler</figcaption>

</figure>

When clicking **Save** or **Delete** in the appointment editor, it is necessary to update the WinUI Scheduler and the SQLite database.

## Perform CRUD operations with SQLite database and update in the WinUI Scheduler

Let’s see how to execute CRUD actions on the SQLite database and synchronize the changes with the WinUI Scheduler control using the Scheduler appointment editor.

### Save an appointment

You can add appointments by providing the required details and clicking the Save button in the appointment editor. The following code example illustrates the command associated with the Save button.

**SchedulerViewModel.cs**

```csharp
internal async void AddAppointmentDetails(string action, ScheduleAppoint-ment scheduleAppointment)
{
    appointment = scheduleAppointment;
    var endDate = appointment.ActualEndTime.Date;
    var startDate = appointment.ActualStartTime.Date;
    var endTime = appointment.ActualEndTime.TimeOfDay;
    var startTime = appointment.ActualStartTime.TimeOfDay;
    if (endDate < startDate)
    {
        await ShowDisplayAlert("End date should be greater than start date");
    }
    else if (!appointment.IsAllDay && endDate == startDate)
    {
        if (endTime <= startTime)
        {
            await ShowDisplayAlert("End time should be greater than start time");
        }
        else
        {
            AppointmentDetails(action, appointment);
        }
    }
    else
    {
        AppointmentDetails(action, appointment);
    }
}
private void AppointmentDetails(string action, ScheduleAppointment scheduleAp-pointment)
{
    if (action == "Add" && this.Appointments != null)
    {
        appointment.Id = Appointments.Count;
        //// Add the appointments in the Scheduler.
        Appointments.Add(appointment);
    }
    SaveSchedulerAppointmentAsync();
}
```

Refer to the following code example to save an appointment in the SQLite database.

**SchedulerViewModel.cs**

```csharp
private void SaveSchedulerAppointmentAsync()
{
      //// - add or edit the appointment in the database collection.
      var editAppointment = new Appointment() { From = appointment.StartTime, To = appointment.EndTime, AllDay = appointment.IsAllDay, Notes = appointment.Notes, EventName = appointment.Subject, Id = (int)appointment.Id };
      App.Database.SaveSchedulerAppointment(editAppointment);
}
```

**SchedulerDatabase.cs**

```csharp
//Insert an appointment in the database.
public int SaveSchedulerAppointment(Appointment appointment)
{
    return sqLiteConnection.InsertOrReplace(appointment);
}
```

### Deleting an appointment

By clicking the Delete button, we can delete an appointment in the WinUI Scheduler and the SQLite database. The following code examples demonstrate the command associated with the Delete button.

**SchedulerViewModel.cs**

```csharp
internal void DeleteSchedulerAppointment(ScheduleAppointment scheduleAppointment)
{
    appointment = scheduleAppointment;

    //// Remove the appointments from the Scheduler.
    Appointments.Remove(this.appointment);
    //// Delete appointment from the database.
    var deleteAppointment = new Appointment() { From = appointment.StartTime, To = appointment.EndTime, AllDay = appointment.IsAllDay, Notes = appointment.Notes, EventName = appointment.Subject, Id = (int)appointment.Id };
    App.Database.DeleteSchedulerAppointment(deleteAppointment);
}
```

**SchedulerDatabase.cs**

```csharp
public int DeleteSchedulerAppointment(Appointment appointment)
{
    return sqLiteConnection.Delete(appointment);
}
```

<figure>

  <img src="https://www.syncfusion.com/blogs/wp-content/uploads/2024/02/Performing-CRUD-operations-in-SQLite-database-using-WinUI-Scheduler.gif" alt="Performing CRUD operations in SQLite database using WinUI Scheduler" style="width:100%">

  <figcaption>Performing CRUD operations in SQLite database using WinUI Scheduler</figcaption>

</figure>

When rerunning the application, the WinUI Scheduler will fetch the updated appointments from the SQLite database, and the output will be as follows.

<figure>

  <img src="https://www.syncfusion.com/blogs/wp-content/uploads/2024/02/Updating-the-WinUI-Scheduler-appointments-from-the-SQLite-database.png" alt="Updating the WinUI Scheduler appointments from the SQLite database" style="width:100%">

  <figcaption>Updating the WinUI Scheduler appointments from the SQLite database</figcaption>

</figure>

## Conclusion

Thanks for reading! In this blog, we learned how to load appointments in the [WinUI Scheduler](https://www.syncfusion.com/winui-controls/scheduler "Syncfusion WinUI Scheduler") with the SQLite database and perform CRUD operations with ease. Try out the steps discussed in this blog and leave your feedback in the comments section below!

Existing customers can access the new version of Essential Studio from the [License and Downloads](https://www.syncfusion.com/account/downloads "Essential Studio License and Downloads page") page. If you’re not a Syncfusion customer, why not explore our features with our 30-day [free trial](https://www.syncfusion.com/downloads "Get the free 30-day evaluation of Essential Studio products")?

For questions, you can contact us through our [support forum](https://www.syncfusion.com/forums "Syncfusion Support Forum"), [support portal](https://support.syncfusion.com/ "Syncfusion Support Portal"), or [feedback portal](https://www.syncfusion.com/feedback/winui "Syncfusion Feedback Portal"). We’re here to help you every step of the way!

## Related blogs

- [From Stars to Hearts: Explore Creative Rating Designs in WinUI](https://www.syncfusion.com/blogs/post/creative-rating-designs-winui.aspx "Blog: From Stars to Hearts: Explore Creative Rating Designs in WinUI")
- [What’s New in 2023 Volume 4: WinUI and WPF](https://www.syncfusion.com/blogs/post/2023-vol-4-winui-wpf.aspx "Blog: What’s New in 2023 Volume 4: WinUI and WPF")
- [Chart of the Week: Creating a WinUI Stacked Area Chart to Visualize US Primary Energy Consumption](https://www.syncfusion.com/blogs/post/winui-stacked-area-chart-energy-consumption.aspx "Blog: Chart of the Week: Creating a WinUI Stacked Area Chart to Visualize US Primary Energy Consumption")
- [Introducing the New WinUI Shimmer Control](https://www.syncfusion.com/blogs/post/new-winui-shimmer-control.aspx "Blog: Introducing the New WinUI Shimmer Control")
- [Unleashing the Power of Navigation and Filtering with WinUI Segmented Control](https://www.syncfusion.com/blogs/post/navigation-filtering-winui-segmented-control.aspx "Blog: Unleashing the Power of Navigation and Filtering with WinUI Segmented Control")