【问题标题】:Chart DataBinding to DataTable - Chart Not Updating图表数据绑定到数据表 - 图表未更新
【发布时间】:2013-09-11 14:34:28
【问题描述】:

我正在尝试将 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();
}

【问题讨论】:

    标签: c# winforms data-binding charts


    【解决方案1】:

    尝试将表用作数据源:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2010-10-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-07-08
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多