I'm attempting to databind a Chart
to a DataTable
. I would like the chart to display new rows as they are added, but the chart is not updating when new rows are added to the table. I have verified that both table
and tableDataSource
contain the new rows, but chart.Series["TestTable"].Points.Count
never changes from 5
.
Sample code, based on the question Can't bind datatable to Chart Control, is shown below. I would either like to know if there is an error or omission with the code below, or a different, better approach that achieves the same objective. I know how to manually add points to a Series
, but I would like to see how to do this using data binding.
Random r = new Random();
Timer timer = new Timer();
DataTable table = new DataTable("TestTable");
DateTime date = new DateTime(2013, 1, 1);
IList tableDataSource = null;
void timer_Tick(object sender, EventArgs e)
{
table.Rows.Add(date, r.NextDouble());
date = date.AddDays(1);
chart.Update();
}
void MainForm_Load(object sender, EventArgs e)
{
table.Columns.Add("Date", typeof(DateTime));
table.Columns.Add("Percent", typeof(double));
for (int i = 0; i < 5; i++)
{
table.Rows.Add(date, r.NextDouble());
date = date.AddDays(1);
}
tableDataSource = (table as IListSource).GetList();
chart.DataBindTable(tableDataSource, "Date");
timer.Interval = 500;
timer.Tick += new EventHandler(timer_Tick);
timer.Start();
}
Try using the table as a DataSource instead:
// tableDataSource = (table as IListSource).GetList();
// chart.DataBindTable(tableDataSource, "Date");
chart.Series.Add("test");
chart.Series["test"].XValueMember = "Date";
chart.Series["test"].YValueMembers = "Percent";
chart.DataSource = table;
chart.DataBind();
and then in the tick event, call DataBind again instead of the Update:
void timer_Tick(object sender, EventArgs e) {
table.Rows.Add(date, r.NextDouble());
date = date.AddDays(1);
//chart.Update();
chart.DataBind();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With