Skip to content

Commit 4e0632e

Browse files
committed
update README.md
1 parent e69e554 commit 4e0632e

File tree

3 files changed

+80
-56
lines changed

3 files changed

+80
-56
lines changed

README.md

Lines changed: 78 additions & 54 deletions
Original file line numberDiff line numberDiff line change
@@ -1,77 +1,101 @@
1-
# How to bind the SQL Database in UWP Chart (SfChart)?
1+
# How to bind the SQL Database in UWP Chart?
22

33
This example illustrates how to establish the SQL connection and bind the retrieving data from database in a step by step process:
44

5-
**Step 1:** Retrieve the data table from the SQL DataSet using the connection string.
6-
```
5+
**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.
6+
```csharp
77
public class ViewModel
88
{
9-
public ViewModel()
10-
{
11-
try
12-
{
13-
SqlConnection thisConnection = new SqlConnection(ConnectionString);
14-
thisConnection.Open();
15-
string Get_Data = "SELECT * FROM ChartData";
16-
SqlCommand cmd = thisConnection.CreateCommand();
17-
cmd.CommandText = Get_Data;
18-
SqlDataAdapter sda = new SqlDataAdapter(cmd);
19-
DataSet ds = new DataSet();
20-
sda.Fill(ds);
21-
var table = ds.Tables[0];
22-
this.DataTable = table;
23-
}
24-
catch
25-
{
26-
return;
27-
}
28-
}
9+
public ObservableCollection<ChartDataItem> DataTable { get; } = new ObservableCollection<ChartDataItem>();
2910

30-
public object DataTable { get; set; }
11+
. . .
3112

32-
public static string ConnectionString
13+
// Creates a SQLite DB in LocalFolder on first run and seeds simple rows
14+
private static async Task<string> EnsureAndSeedDatabaseAsync(string dbFileName)
3315
{
34-
get
16+
var localFolder = ApplicationData.Current.LocalFolder;
17+
var existing = await localFolder.TryGetItemAsync(dbFileName);
18+
var dbPath = Path.Combine(localFolder.Path, dbFileName);
19+
20+
if (existing == null)
3521
{
36-
string currentDir = System.Environment.CurrentDirectory;
37-
currentDir = currentDir.Substring(0, currentDir.Length - 10) + "\\LocalDataBase";
38-
return @"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=" + currentDir + @"\SeriesItemsSource.mdf;Integrated Security=True";
22+
using (var connection = new SqliteConnection($"Data Source={dbPath}"))
23+
{
24+
await connection.OpenAsync();
25+
26+
// Create table
27+
using (var create = connection.CreateCommand())
28+
{
29+
create.CommandText = @"
30+
CREATE TABLE IF NOT EXISTS ChartData (
31+
xValue REAL NOT NULL,
32+
yValue REAL NOT NULL
33+
);";
34+
await create.ExecuteNonQueryAsync();
35+
}
36+
37+
// Seed a few sample points
38+
using (var tx = connection.BeginTransaction())
39+
using (var insert = connection.CreateCommand())
40+
{
41+
insert.CommandText = "INSERT INTO ChartData (xValue, yValue) VALUES ($x, $y)";
42+
var px = insert.CreateParameter(); px.ParameterName = "$x"; insert.Parameters.Add(px);
43+
var py = insert.CreateParameter(); py.ParameterName = "$y"; insert.Parameters.Add(py);
44+
45+
var points = new (double x, double y)[]
46+
{
47+
(1, 10), (2, 14), (3, 9), (4, 18), (5, 22), (6, 17), (7, 25)
48+
};
49+
50+
foreach (var (x, y) in points)
51+
{
52+
px.Value = x;
53+
py.Value = y;
54+
await insert.ExecuteNonQueryAsync();
55+
}
56+
57+
tx.Commit();
58+
}
59+
}
3960
}
61+
62+
return dbPath;
4063
}
4164
}
4265
```
4366

44-
**Step 2:** In the main page, initialize the SfChart control and bind the retrieved data.
45-
```
67+
**Step 2:** Set up the [SfChart](https://help.syncfusion.com/cr/uwp/Syncfusion.UI.Xaml.Charts.SfChart.html) 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.
68+
```xml
4669
<Grid>
47-
        <Grid.DataContext>
48-
            <local:ViewModel></local:ViewModel>
49-
        </Grid.DataContext>
50-
       
51-
        <chart:SfChart Margin="10">
52-
           
53-
            <chart:SfChart.PrimaryAxis>
54-
                <chart:NumericalAxis RangePadding="Additional"/>
55-
            </chart:SfChart.PrimaryAxis>
56-
 
57-
            <chart:SfChart.SecondaryAxis>
58-
                <chart:NumericalAxis RangePadding="Additional"/>
59-
            </chart:SfChart.SecondaryAxis>
60-
 
61-
            <chart:ScatterSeries ItemsSource="{Binding DataTable}"
62-
                                XBindingPath="xVal"
63-
                                YBindingPath="yVal"/>
64-
        </chart:SfChart>
65-
       
70+
<Grid.DataContext>
71+
<local:ViewModel/>
72+
</Grid.DataContext>
73+
74+
<chart:SfChart Margin="10">
75+
76+
<chart:SfChart.PrimaryAxis>
77+
<chart:NumericalAxis RangePadding="Additional" />
78+
</chart:SfChart.PrimaryAxis>
79+
80+
<chart:SfChart.SecondaryAxis>
81+
<chart:NumericalAxis RangePadding="Additional" />
82+
</chart:SfChart.SecondaryAxis>
83+
84+
<chart:ScatterSeries ItemsSource="{Binding DataTable}"
85+
XBindingPath="XValue"
86+
YBindingPath="YValue" />
87+
</chart:SfChart>
6688
</Grid>
6789
```
6890

69-
## Output:
91+
## Output
7092

7193
![SQL DataBinding to UWP SfChart](https://user-images.githubusercontent.com/53489303/200761566-1e210d5c-0740-4a08-9b58-8cc264ff0691.png)
7294

73-
KB article - [How to bind the SQL Database in UWP Chart (SfChart)?](https://www.syncfusion.com/kb/11664/how-to-bind-the-sql-database-in-uwp-chart)
95+
## Troubleshooting
96+
97+
### Path Too Long Exception
7498

75-
## See also
99+
If you are facing a "Path too long" exception when building this example project, close Visual Studio and rename the repository to a shorter name before building the project.
76100

77-
[How to bind the SQL Database to WPF Charts](https://www.syncfusion.com/kb/11595/how-to-bind-the-sql-database-to-wpf-charts)
101+
Refer to the knowledge base article [How to bind the SQL Database in UWP Chart]().

SQLiteChartBinding_UWP/MainPage.xaml.cs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,7 @@ public sealed partial class MainPage : Page
1111
{
1212
public MainPage()
1313
{
14-
this.InitializeComponent();
14+
InitializeComponent();
1515
}
1616
}
1717
}

SQLiteChartBinding_UWP/ViewModel/ViewModel.cs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -73,7 +73,7 @@ yValue REAL NOT NULL
7373
await create.ExecuteNonQueryAsync();
7474
}
7575

76-
// Seed a few sample points (you can change these)
76+
// Seed a few sample points
7777
using (var tx = connection.BeginTransaction())
7878
using (var insert = connection.CreateCommand())
7979
{

0 commit comments

Comments
 (0)