Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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();
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
308 views
Welcome To Ask or Share your Answers For Others

1 Answer

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...