Articles in this section
Category / Section

How to bind the SQL Database in UWP Chart?

This article explains how to establish an SQL connection and bind the retrieved data from a database to UWP Chart.

Step 1: Create a ViewModel class that establishes a connection to your SQLite database, executes a query, and retrieves the data into an ObservableCollection<ChartDataItem>. The database file is created and seeded in the app’s local folder on first run in this example.

public class ViewModel
{
    public ObservableCollection<ChartDataItem> DataTable { get; } = new ObservableCollection<ChartDataItem>();

    public ViewModel()
    {
        _ = InitializeAsync();
    }

    private async Task InitializeAsync()
    {
        try
        {
            string dbPath = await EnsureAndSeedDatabaseAsync("DataSource.sqlite");

            using (var connection = new SqliteConnection($"Data Source={dbPath}"))
            {
                await connection.OpenAsync();

                using (var cmd = connection.CreateCommand())
                {
                    cmd.CommandText = "SELECT xValue, yValue FROM ChartData";
                    using (var reader = await cmd.ExecuteReaderAsync())
                    {
                        while (await reader.ReadAsync())
                        {
                            DataTable.Add(new ChartDataItem
                            {
                                XValue = reader.GetDouble(0),
                                YValue = reader.GetDouble(1)
                            });
                        }
                    }
                }
            }
        }
        catch (Exception ex)
        {
            System.Diagnostics.Debug.WriteLine("SQLite init/load error: " + ex.Message);
        }
    }

    // Creates a SQLite DB in LocalFolder on first run and seeds simple rows
    private static async Task<string> EnsureAndSeedDatabaseAsync(string dbFileName)
    {
        var localFolder = ApplicationData.Current.LocalFolder;
        var existing = await localFolder.TryGetItemAsync(dbFileName);
        var dbPath = Path.Combine(localFolder.Path, dbFileName);

        if (existing == null)
        {
            using (var connection = new SqliteConnection($"Data Source={dbPath}"))
            {
                await connection.OpenAsync();

                // Create table
                using (var create = connection.CreateCommand())
                {
                    create.CommandText = @"
                        CREATE TABLE IF NOT EXISTS ChartData (
                            xValue REAL NOT NULL,
                            yValue REAL NOT NULL
                        );";
                    await create.ExecuteNonQueryAsync();
                }

                // Seed a few sample points
                using (var tx = connection.BeginTransaction())
                using (var insert = connection.CreateCommand())
                {
                    insert.CommandText = "INSERT INTO ChartData (xValue, yValue) VALUES ($x, $y)";
                    var px = insert.CreateParameter(); px.ParameterName = "$x"; insert.Parameters.Add(px);
                    var py = insert.CreateParameter(); py.ParameterName = "$y"; insert.Parameters.Add(py);

                    var points = new (double x, double y)[]
                    {
                        (1, 10), (2, 14), (3, 9), (4, 18), (5, 22), (6, 17), (7, 25)
                    };

                    foreach (var (x, y) in points)
                    {
                        px.Value = x;
                        py.Value = y;
                        await insert.ExecuteNonQueryAsync();
                    }

                    tx.Commit();
                }
            }
        }

        return dbPath;
    }
}

Step 2: Set up the SfChart control with appropriate axes and bind the ItemsSource of a chart series to the DataTable property from your ViewModel. Specify the XBindingPath and YBindingPath to map to the respective columns in your database table.

<Grid>
    <Grid.DataContext>
        <local:ViewModel/>
    </Grid.DataContext>

    <chart:SfChart Margin="10">

        <chart:SfChart.PrimaryAxis>
            <chart:NumericalAxis RangePadding="Additional" />
        </chart:SfChart.PrimaryAxis>

        <chart:SfChart.SecondaryAxis>
            <chart:NumericalAxis RangePadding="Additional" />
        </chart:SfChart.SecondaryAxis>

        <chart:ScatterSeries ItemsSource="{Binding DataTable}"
                             XBindingPath="XValue"
                             YBindingPath="YValue" />
    </chart:SfChart>
</Grid>

Output

Output image of SfChart rendered using SQL DataBinding.


Refer to the Github sample to examine the full working implementation.

Conclusion

I hope you enjoyed learning about how to bind the SQL Database in UWP Chart.

You can refer to our UWP Chart’s feature tour page to know about its other groundbreaking feature representations. You can also explore our UWP Chart documentation to understand how to present and manipulate data.

For current customers, you can check out our WinForms components from the License and Downloads page. If you are new to Syncfusion®, you can try our 30-day free trial to check out our UWP Charts and other UWP components.

If you have any queries or require clarifications, please let us know in comments below. You can also contact us through our support forumsDirect-Trac, or feedback portal. We are always happy to assist you!

Did you find this information helpful?
Yes
No
Help us improve this page
Please provide feedback or comments
Comments (0)
Access denied
Access denied