madfase 0 Newbie Poster

Problem: How do you dynamically update a chart / graph in a single iteration loop in Visual Studio 2010 WinForms C# application?

Scenario: I'm doing simulation-based computations where I have an array to represent values for my function along an interval. The function is time-dependant and so the values in the array will change in time.

I can display the function values on the chart, but I cannot get them to update dynamically. For purely illustrative purposes, consider the following simplified example:

You have a bar that is being heated. The length of the bar is 100cm. The array "Temperature" stores the temperature of the bar at every 1 cm interval (so the array has 100 elements). I graph it as follows:

for (int i = 0; i < 100; i++)
{
  chart1.Series[0].Points.AddXY(i, Temperature[i]);
}

Now, I perform a bunch of computations and update the temperature profile. But to update the chart / graph, I try the following code, which works:

for (int j = 0; j < 100; j++)
{
  chart1.Series[0].Points.RemoveAt(0);
}

for (int k = 0; k < 100; k++)
{
  chart1.Series[0].Points.AddXY(i, Temperature_new[k]);
}

However, the problem comes when the above computations and updates occur within a loop inside a single method. So, when I click the button on my GUI to begin the simulations, I would have something like this:

private void buttonStartSimulation_Click(object sender, EventArgs e)
  // Graph initial temperature profile
  for (int i = 0; i < 100; i++)
  {
    chart1.Series[0].Points.AddXY(i, Temperature[i]);
  }

  // Simulation loop
  for (int i = 0; i < SimulationRunTime ; i++)
  {
    // Perform calculations for a new temperature profile
    // ...

    // ...

    // Update graphs
    for (int j = 0; j < 100; j++)
    {
      chart1.Series[0].Points.RemoveAt(0);
    }

    for (int j = 0; j < 100; j++)
    {
      chart1.Series[0].Points.AddXY(i, Temperature_new[j]);
    }
  }
}

The problem is is that the graphs wont update at every iteration in the loop. The program cycles through all the iterations and only updates the graph after the very last iteration. In other words, it seems that the update is only happening at the end of the event triggered by the button click. I tried using System.Threading.Thread.Sleep(...) to pause in between updating the chart to see if that helps, but nothing. The fact that it's not a time issue (I've tried using values where the program would sleep for a minute in between each iteration), suggests that the chart update is somehow event-driven in addition to the button click.

So, how would I get my chart / graph to update within the iteration loop?