|
1 |
| -# How-to-bind-the-SQL-Database-to-WPF-Charts |
| 1 | +# How to bind the SQL Database to WPF Chart (SfChart)? |
2 | 2 |
|
3 |
| -KB article - [How-to-bind-the-SQL-Database-to-WPF-Charts](https://www.syncfusion.com/kb/11595/how-to-bind-the-sql-database-to-wpf-charts) |
| 3 | +This example demonstrates how to establish the SQL connection and bind the retrieving data from database in a step by step process. |
| 4 | + |
| 5 | +**Step 1:** Retrieve the data table from the SQL DataSet using the connection string. |
| 6 | + |
| 7 | +``` |
| 8 | +public class ViewModel |
| 9 | +{ |
| 10 | + public ViewModel() |
| 11 | + { |
| 12 | + try |
| 13 | + { |
| 14 | + SqlConnection thisConnection = new SqlConnection(ConnectionString); |
| 15 | + thisConnection.Open(); |
| 16 | + string Get_Data = "SELECT * FROM ChartData"; |
| 17 | + SqlCommand cmd = thisConnection.CreateCommand(); |
| 18 | + cmd.CommandText = Get_Data; |
| 19 | + SqlDataAdapter sda = new SqlDataAdapter(cmd); |
| 20 | + DataSet ds = new DataSet(); |
| 21 | + sda.Fill(ds); |
| 22 | + var table = ds.Tables[0]; |
| 23 | + this.DataTable = table; |
| 24 | + } |
| 25 | + catch |
| 26 | + { |
| 27 | + MessageBox.Show("DataBase Error"); |
| 28 | + } |
| 29 | + } |
| 30 | +
|
| 31 | + public object DataTable { get; set; } |
| 32 | +
|
| 33 | + public static string ConnectionString |
| 34 | + { |
| 35 | + get |
| 36 | + { |
| 37 | + string currentDir = System.Environment.CurrentDirectory; |
| 38 | + currentDir = currentDir.Substring(0, currentDir.Length - 10) + "\\LocalDataBase"; |
| 39 | + return @"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=" + currentDir + @"\SeriesItemsSource.mdf;Integrated Security=True"; |
| 40 | + } |
| 41 | + } |
| 42 | +} |
| 43 | +``` |
| 44 | + |
| 45 | +**Step 2:** In the main page, initialize the SfChart control and bind the retrieved data. |
| 46 | +``` |
| 47 | +<Grid> |
| 48 | + <Grid.DataContext> |
| 49 | + <local:ViewModel></local:ViewModel> |
| 50 | + </Grid.DataContext> |
| 51 | + |
| 52 | + <chart:SfChart Margin="10"> |
| 53 | + |
| 54 | + <chart:SfChart.PrimaryAxis> |
| 55 | + <chart:NumericalAxis RangePadding="Additional"/> |
| 56 | + </chart:SfChart.PrimaryAxis> |
| 57 | +
|
| 58 | + <chart:SfChart.SecondaryAxis> |
| 59 | + <chart:NumericalAxis RangePadding="Additional"/> |
| 60 | + </chart:SfChart.SecondaryAxis> |
| 61 | +
|
| 62 | + <chart:ScatterSeries ItemsSource="{Binding DataTable}" |
| 63 | + XBindingPath="xVal" |
| 64 | + YBindingPath="yVal"/> |
| 65 | + </chart:SfChart> |
| 66 | + |
| 67 | +</Grid> |
| 68 | +``` |
| 69 | + |
| 70 | +## Output: |
| 71 | + |
| 72 | + |
| 73 | + |
| 74 | +KB article - [How to bind the SQL Database to WPF Charts?](https://www.syncfusion.com/kb/11595/how-to-bind-the-sql-database-to-wpf-charts) |
0 commit comments