How to bind the SQL Database to WPF Charts?
This article explains how to establish the SQL connection and bind the retrieved data from database in a step-by-step process.
Step 1: Retrieve the DataTable from the SQL DataSet using the connection string.
public class ViewModel { public ViewModel() { try { SqlConnection thisConnection = new SqlConnection(ConnectionString); thisConnection.Open(); string Get_Data = "SELECT * FROM ChartData"; SqlCommand cmd = thisConnection.CreateCommand(); cmd.CommandText = Get_Data; SqlDataAdapter sda = new SqlDataAdapter(cmd); DataSet ds = new DataSet(); sda.Fill(ds); var table = ds.Tables[0]; this.DataTable = table; } catch { MessageBox.Show("DataBase Error"); } } public object DataTable { get; set; } public static string ConnectionString { get { string currentDir = System.Environment.CurrentDirectory; currentDir = currentDir.Substring(0, currentDir.Length - 10) + "\\LocalDataBase"; return @"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=" + currentDir + @"\SeriesItemsSource.mdf;Integrated Security=True"; } } }
Step 2: In the main page, initialize the SfChart control and bind the retrieved data.
<Grid> <Grid.DataContext> <local:ViewModel></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="xVal" YBindingPath="yVal"/> </chart:SfChart> </Grid>
Output
For more details, please refer to the project on GitHub.
Conclusion
I hope you enjoyed learning how to bind the SQL Database to WPF Charts.
You can refer to our WPF Chart feature tour page know about its other groundbreaking feature representations and documentation, and how to quickly get started for configuration specifications. You can also explore our WPF Chart Examples to understand how to create and manipulate data.
For current customers, you can check out our 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 other controls.
If you have any queries or require clarifications, please let us know in the comments section below. You can also contact us through our support forums, Direct-Trac, or feedback portal. We are always happy to assist you!