How to Populate .NET MAUI DataGrid using a Sqlite Database?
This article demonstrates how to populate a .NET MAUI DataGrid using a SQLite database file already existing in the Windows file system.
Xaml
<ContentPage.BindingContext>
<local:ProductsViewModel x:Name="viewModel" />
</ContentPage.BindingContext>
<syncfusion:SfDataGrid ItemsSource="{Binding Products}"
ColumnWidthMode="Auto"
GridLinesVisibility="Both"
HeaderGridLinesVisibility="Both" />
DatabaseService.cs file
The code below demonstrates how to handle database operations in a .NET MAUI application using SQLite asynchronously.
public class DatabaseService
{
private readonly SQLiteAsyncConnection _database;
private readonly string _dbPath;
public DatabaseService()
{
// NOTE: Don't forget to update the database path to match your machine's directory.
_dbPath = @"D:\Support\MarchSupport\703516\products.db";
// Check if file exists before connecting
if (!File.Exists(_dbPath))
{
throw new FileNotFoundException($"Database file not found at {_dbPath}");
}
_database = new SQLiteAsyncConnection(_dbPath);
}
public async Task<List<Products>> GetProductsAsync()
{
return await _database.Table<Products>().ToListAsync();
}
}
ProductViewModel.cs file
This ProductsViewModel class is responsible for managing and displaying product data in a UI using the MVVM pattern.
public class ProductsViewModel
{
public ObservableCollection<Products> Products { get; set; } = new();
private readonly DatabaseService _databaseService;
public ProductsViewModel()
{
_databaseService = new DatabaseService();
LoadData();
}
private async void LoadData()
{
var items = await _databaseService.GetProductsAsync();
foreach (var item in items)
{
Products.Add(item);
}
}
}
Output
Download the complete sample from GitHub.
Conclusion
I hope you enjoyed learning how to populate .NET MAUI DataGrid using a SQLite database.
You can refer to our .NET MAUI DataGrid feature tour page to learn about its other groundbreaking feature representations and Documentation, and how to quickly get started with configuration specifications. Explore our .NET MAUI DataGrid example to understand how to create and manipulate data.
For current customers, check out our components from the License and Downloads page. If you are new to Syncfusion®, try our 30-day free trial to check out our other controls.
Please let us know in the comments section if you have any queries or require clarification. You can also contact us through our support forums, Direct-Trac, or feedback portal. We are always happy to assist you!