Skip to content

Commit ef865fc

Browse files
Merge pull request #4 from SyncfusionExamples/update-sample
Update Sample: Resolve the Database connection issue in the UWP Sample application
2 parents 0de6d84 + a411b9a commit ef865fc

23 files changed

+679
-614
lines changed

README.md

Lines changed: 78 additions & 55 deletions
Original file line numberDiff line numberDiff line change
@@ -1,77 +1,100 @@
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
92+
<img width="1139" height="682" alt="image" src="https://github.com/user-attachments/assets/150d7535-ff50-436a-8fcb-0d9f4ec39bdf" />
7093

71-
![SQL DataBinding to UWP SfChart](https://user-images.githubusercontent.com/53489303/200761566-1e210d5c-0740-4a08-9b58-8cc264ff0691.png)
94+
## Troubleshooting
7295

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)
96+
### Path Too Long Exception
7497

75-
## See also
98+
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.
7699

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)
100+
Refer to the knowledge base article [How to bind the SQL Database in UWP Chart](https://support.syncfusion.com/kb/article/10133/how-to-bind-the-sql-database-in-uwp-chart).
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
1-
<Application
2-
x:Class="SQLLiteChartBinding.App"
3-
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
4-
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
5-
xmlns:local="using:SQLLiteChartBinding">
6-
7-
</Application>
1+
<Application
2+
x:Class="SQLiteChartBinding_UWP.App"
3+
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
4+
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
5+
xmlns:local="using:SQLiteChartBinding_UWP">
6+
7+
</Application>
Original file line numberDiff line numberDiff line change
@@ -1,100 +1,100 @@
1-
using System;
2-
using System.Collections.Generic;
3-
using System.IO;
4-
using System.Linq;
5-
using System.Runtime.InteropServices.WindowsRuntime;
6-
using Windows.ApplicationModel;
7-
using Windows.ApplicationModel.Activation;
8-
using Windows.Foundation;
9-
using Windows.Foundation.Collections;
10-
using Windows.UI.Xaml;
11-
using Windows.UI.Xaml.Controls;
12-
using Windows.UI.Xaml.Controls.Primitives;
13-
using Windows.UI.Xaml.Data;
14-
using Windows.UI.Xaml.Input;
15-
using Windows.UI.Xaml.Media;
16-
using Windows.UI.Xaml.Navigation;
17-
18-
namespace SQLLiteChartBinding
19-
{
20-
/// <summary>
21-
/// Provides application-specific behavior to supplement the default Application class.
22-
/// </summary>
23-
sealed partial class App : Application
24-
{
25-
/// <summary>
26-
/// Initializes the singleton application object. This is the first line of authored code
27-
/// executed, and as such is the logical equivalent of main() or WinMain().
28-
/// </summary>
29-
public App()
30-
{
31-
this.InitializeComponent();
32-
this.Suspending += OnSuspending;
33-
}
34-
35-
/// <summary>
36-
/// Invoked when the application is launched normally by the end user. Other entry points
37-
/// will be used such as when the application is launched to open a specific file.
38-
/// </summary>
39-
/// <param name="e">Details about the launch request and process.</param>
40-
protected override void OnLaunched(LaunchActivatedEventArgs e)
41-
{
42-
Frame rootFrame = Window.Current.Content as Frame;
43-
44-
// Do not repeat app initialization when the Window already has content,
45-
// just ensure that the window is active
46-
if (rootFrame == null)
47-
{
48-
// Create a Frame to act as the navigation context and navigate to the first page
49-
rootFrame = new Frame();
50-
51-
rootFrame.NavigationFailed += OnNavigationFailed;
52-
53-
if (e.PreviousExecutionState == ApplicationExecutionState.Terminated)
54-
{
55-
//TODO: Load state from previously suspended application
56-
}
57-
58-
// Place the frame in the current Window
59-
Window.Current.Content = rootFrame;
60-
}
61-
62-
if (e.PrelaunchActivated == false)
63-
{
64-
if (rootFrame.Content == null)
65-
{
66-
// When the navigation stack isn't restored navigate to the first page,
67-
// configuring the new page by passing required information as a navigation
68-
// parameter
69-
rootFrame.Navigate(typeof(MainPage), e.Arguments);
70-
}
71-
// Ensure the current window is active
72-
Window.Current.Activate();
73-
}
74-
}
75-
76-
/// <summary>
77-
/// Invoked when Navigation to a certain page fails
78-
/// </summary>
79-
/// <param name="sender">The Frame which failed navigation</param>
80-
/// <param name="e">Details about the navigation failure</param>
81-
void OnNavigationFailed(object sender, NavigationFailedEventArgs e)
82-
{
83-
throw new Exception("Failed to load Page " + e.SourcePageType.FullName);
84-
}
85-
86-
/// <summary>
87-
/// Invoked when application execution is being suspended. Application state is saved
88-
/// without knowing whether the application will be terminated or resumed with the contents
89-
/// of memory still intact.
90-
/// </summary>
91-
/// <param name="sender">The source of the suspend request.</param>
92-
/// <param name="e">Details about the suspend request.</param>
93-
private void OnSuspending(object sender, SuspendingEventArgs e)
94-
{
95-
var deferral = e.SuspendingOperation.GetDeferral();
96-
//TODO: Save application state and stop any background activity
97-
deferral.Complete();
98-
}
99-
}
100-
}
1+
using System;
2+
using System.Collections.Generic;
3+
using System.IO;
4+
using System.Linq;
5+
using System.Runtime.InteropServices.WindowsRuntime;
6+
using Windows.ApplicationModel;
7+
using Windows.ApplicationModel.Activation;
8+
using Windows.Foundation;
9+
using Windows.Foundation.Collections;
10+
using Windows.UI.Xaml;
11+
using Windows.UI.Xaml.Controls;
12+
using Windows.UI.Xaml.Controls.Primitives;
13+
using Windows.UI.Xaml.Data;
14+
using Windows.UI.Xaml.Input;
15+
using Windows.UI.Xaml.Media;
16+
using Windows.UI.Xaml.Navigation;
17+
18+
namespace SQLiteChartBinding_UWP
19+
{
20+
/// <summary>
21+
/// Provides application-specific behavior to supplement the default Application class.
22+
/// </summary>
23+
sealed partial class App : Application
24+
{
25+
/// <summary>
26+
/// Initializes the singleton application object. This is the first line of authored code
27+
/// executed, and as such is the logical equivalent of main() or WinMain().
28+
/// </summary>
29+
public App()
30+
{
31+
this.InitializeComponent();
32+
this.Suspending += OnSuspending;
33+
}
34+
35+
/// <summary>
36+
/// Invoked when the application is launched normally by the end user. Other entry points
37+
/// will be used such as when the application is launched to open a specific file.
38+
/// </summary>
39+
/// <param name="e">Details about the launch request and process.</param>
40+
protected override void OnLaunched(LaunchActivatedEventArgs e)
41+
{
42+
Frame rootFrame = Window.Current.Content as Frame;
43+
44+
// Do not repeat app initialization when the Window already has content,
45+
// just ensure that the window is active
46+
if (rootFrame == null)
47+
{
48+
// Create a Frame to act as the navigation context and navigate to the first page
49+
rootFrame = new Frame();
50+
51+
rootFrame.NavigationFailed += OnNavigationFailed;
52+
53+
if (e.PreviousExecutionState == ApplicationExecutionState.Terminated)
54+
{
55+
//TODO: Load state from previously suspended application
56+
}
57+
58+
// Place the frame in the current Window
59+
Window.Current.Content = rootFrame;
60+
}
61+
62+
if (e.PrelaunchActivated == false)
63+
{
64+
if (rootFrame.Content == null)
65+
{
66+
// When the navigation stack isn't restored navigate to the first page,
67+
// configuring the new page by passing required information as a navigation
68+
// parameter
69+
rootFrame.Navigate(typeof(MainPage), e.Arguments);
70+
}
71+
// Ensure the current window is active
72+
Window.Current.Activate();
73+
}
74+
}
75+
76+
/// <summary>
77+
/// Invoked when Navigation to a certain page fails
78+
/// </summary>
79+
/// <param name="sender">The Frame which failed navigation</param>
80+
/// <param name="e">Details about the navigation failure</param>
81+
void OnNavigationFailed(object sender, NavigationFailedEventArgs e)
82+
{
83+
throw new Exception("Failed to load Page " + e.SourcePageType.FullName);
84+
}
85+
86+
/// <summary>
87+
/// Invoked when application execution is being suspended. Application state is saved
88+
/// without knowing whether the application will be terminated or resumed with the contents
89+
/// of memory still intact.
90+
/// </summary>
91+
/// <param name="sender">The source of the suspend request.</param>
92+
/// <param name="e">Details about the suspend request.</param>
93+
private void OnSuspending(object sender, SuspendingEventArgs e)
94+
{
95+
var deferral = e.SuspendingOperation.GetDeferral();
96+
//TODO: Save application state and stop any background activity
97+
deferral.Complete();
98+
}
99+
}
100+
}

SQLwithChartUWP/Assets/LockScreenLogo.scale-200.png renamed to SQLiteChartBinding_UWP/Assets/LockScreenLogo.scale-200.png

File renamed without changes.
File renamed without changes.

SQLwithChartUWP/Assets/Square150x150Logo.scale-200.png renamed to SQLiteChartBinding_UWP/Assets/Square150x150Logo.scale-200.png

File renamed without changes.

SQLwithChartUWP/Assets/Square44x44Logo.scale-200.png renamed to SQLiteChartBinding_UWP/Assets/Square44x44Logo.scale-200.png

File renamed without changes.

SQLwithChartUWP/Assets/Square44x44Logo.targetsize-24_altform-unplated.png renamed to SQLiteChartBinding_UWP/Assets/Square44x44Logo.targetsize-24_altform-unplated.png

File renamed without changes.
File renamed without changes.

SQLwithChartUWP/Assets/Wide310x150Logo.scale-200.png renamed to SQLiteChartBinding_UWP/Assets/Wide310x150Logo.scale-200.png

File renamed without changes.

0 commit comments

Comments
 (0)