Articles in this section
Category / Section

How to bind data table in WPF Chart (SfChart)?

1 min read

The DataTable type can be bound to the ItemsSource property in WPF Chart (SfChart).

XAML

<Grid x:Name="grid">
      <Grid.DataContext>
            <local:DataViewModel/>
      </Grid.DataContext>22
      <chart:SfChart>
            <chart:ColumnSeries ItemsSource="{Binding Data}" XBindingPath="ProductName" YBindingPath="UnitsInStock"></chart:ColumnSeries>
      </chart:SfChart>
 </Grid>

 C#

public class DataViewModel 
{
  DataSet dataset = new DataSet();
  public DataViewModel()
  {
            AddData();
  }
  public void AddData()
  {
    //Sets Database connection.
    string connectionString = string.Format("Provider=Microsoft.Jet.OLEDB.4.0; Data Source={0}", @"..\..\Model\DataBase_File.mdb");
    OleDbConnection Connection = new OleDbConnection(connectionString);
    Connection.Open();
    OleDbCommand command = new OleDbCommand("Select Top 10 * from [Products]", Connection);
    OleDbDataAdapter DataAdapter = new OleDbDataAdapter(command);
    DataAdapter.Fill(dataset, "Product");
    //Sets the DataTable to Data property.
    this.Data = dataset.Tables["Product"];
    Connection.Close();
  }
  public DataTable _data;
  public DataTable Data
  {
    get
    {
      return _data;
    }
    set
    {
      _data = value;
    }
  }
}

WPF Chart with Binding Data from DataTable

 

Did you find this information helpful?
Yes
No
Help us improve this page
Please provide feedback or comments
Comments (2)
Please  to leave a comment
SS
skanoko siame

So after linking the database to the chart, how do you go about loading data from the database in real or quick time?

MK
Muneesh Kumar G

Hi Skanoko siame,

 

We have analyzed your requirement and you can achieve this by changing the DataTable collection, which is bind to series ItemsSource as per the below code snippet.

 

Code snippet [C#]:

DispatcherTimer timer = new DispatcherTimer();

        DataViewModel viewModel = new DataViewModel();

        Random rd = new Random();

        string[] names;

        public MainWindow()

        {

            InitializeComponent();

 

            series.ItemsSource = viewModel.Data;

 

            names = new string[] { "Chang", "Ikura", "Kobe", "Peas", "Pepper" };

            timer.Start();

            timer.Tick += timer_Tick;

            timer.Interval = new TimeSpan(0, 0, 0, 0, 100);

        }

      

        void timer_Tick(object sender, EventArgs e)

        {

            viewModel.Data.Rows.RemoveAt(0);

            viewModel.Data.Rows.Add(new Object[] { names[rd.Next(0,4)], rd.Next(4,20) });

        }

 

We have prepared a sample based on this, please find the sample from the following location.

 

Sample: http://www.syncfusion.com/downloads/support/forum/134727/ze/SfChart_DataTable1269039968.zip

 

Hope this helps.

 

Regards,

Muneesh Kumar G.


Access denied
Access denied