图表数据绑定到数据表 - 图表未更新 [英] Chart DataBinding to DataTable - Chart Not Updating

查看:29
本文介绍了图表数据绑定到数据表 - 图表未更新的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.

示例代码,基于问题无法将数据表绑定到图表控件,如下图.我想知道下面的代码是否有错误或遗漏,或者是不同的、更好的方法来实现相同的目标.我知道如何手动向 Series 添加点,但我想看看如何使用数据绑定来做到这一点.

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

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

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

这篇关于图表数据绑定到数据表 - 图表未更新的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆