Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Chart DataBinding to DataTable - Chart Not Updating

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();
}
like image 891
Brett Wolfington Avatar asked Dec 21 '22 00:12

Brett Wolfington


1 Answers

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();
}
like image 70
LarsTech Avatar answered Dec 27 '22 06:12

LarsTech