Chart DataBinding to DataTable - 图表未更新

时间:2013-09-11 14:34:29

标签: c# winforms data-binding charts

我正在尝试将Chart数据绑定到DataTable。我希望图表在添加时显示新行,但在将新行添加到表中时图表不会更新。我已验证tabletableDataSource都包含新行,但chart.Series["TestTable"].Points.Count从不更改5

基于问题Can't bind datatable to Chart Control的示例代码如下所示。我想知道下面的代码是否有错误或遗漏,或者是一种实现相同目标的不同的更好的方法。我知道如何手动将点添加到Series,但我想看看如何使用数据绑定来做到这一点。

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();
}

1 个答案:

答案 0 :(得分:9)

尝试将该表用作DataSource:

// 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();

然后在tick事件中,再次调用DataBind而不是Update:

void timer_Tick(object sender, EventArgs e) {
  table.Rows.Add(date, r.NextDouble());
  date = date.AddDays(1);

  //chart.Update();
  chart.DataBind();
}