C# 图表数据绑定到数据表 - 图表未更新
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18744092/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Chart DataBinding to DataTable - Chart Not Updating
提问by Brett Wolfington
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
.
我正在尝试将 a 数据绑定Chart
到 a DataTable
。我希望图表在添加新行时显示它们,但在向表中添加新行时图表不会更新。我已验证table
和tableDataSource
都包含新行,但chart.Series["TestTable"].Points.Count
从未从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.
基于问题Can't bind datatable to Chart Control 的示例代码如下所示。我想知道下面的代码是否有错误或遗漏,或者是一种不同的、更好的方法来实现相同的目标。我知道如何手动向 a 添加点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();
}
采纳答案by LarsTech
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:
然后在滴答事件中,再次调用 DataBind 而不是 Update:
void timer_Tick(object sender, EventArgs e) {
table.Rows.Add(date, r.NextDouble());
date = date.AddDays(1);
//chart.Update();
chart.DataBind();
}