Ragnar
Ragnar

Reputation: 17

I'm trying to continuously read data from a SQL Server table to a chart in c#

The code does that but it also repeats the old data so the chart isn't quite right

try 
{
    string valueX;
    double valueY;

    SqlConnection con = new SqlConnection(SmartHytte_G4); 
    string sqlQuery = "select * from LOGGTEMPSENSOR"; 

    SqlCommand sql = new SqlCommand(sqlQuery, con);
    con.Open(); //Åpner oppkoblingen

    SqlDataReader dr = sql.ExecuteReader();
    //chart.Series.Clear();

    if (dr.HasRows)
    {
        while (dr.Read() == true)
        {
            valueX = Convert.ToString(dr["TimeStamp"]); 
            valueY = Convert.ToDouble(dr["Value"]);
            chart.Series["Temperatur"].Points.AddXY(valueX, valueY);
        }
    }

    con.Close(); 
}
catch (Exception error) 
{
    MessageBox.Show(error.Message);
}

Sorry for the terrible explanation

Upvotes: 2

Views: 277

Answers (2)

Bob Wood
Bob Wood

Reputation: 81

If you want to stick to your original code you could simply retrieve only the latest data-point in each request:

"select top 1 * from LOGGTEMPSENSOR ORDER BY TimeStamp DESC"

This assumes, however, that you update your chart more often than the data base.

A more robust solution would be to retrieve only the data-points that are newer than the last data-point in the previous chart update.

Upvotes: 1

Karthick Raju
Karthick Raju

Reputation: 797

Clear the chart series before adding:

foreach(var series in chart.Series) {
    series.Points.Clear();
}

Upvotes: 1

Related Questions