I have the following data in a database table,
Columns: Date, Hour(from 1 to 24) and Temperature.
I want to create a line chart that will show in the x-axis the hours from 1 to 24 and in the Y-axis the Temperatures.
Now the tricky part is that I want to have different color lines for each date. So if the date is 2012-01-15 then I have a red line from 1 to 24 showing the variations in temperature. if the date is 2012-01-14 then a blue one also from 1 to 24.
To be clear I want to have multiple dates in one chart.
Here is some of code I have
SqlConnection conn2 = new SqlConnection(@"connectionString");
conn2.Open();
SqlCommand cmd2 = new SqlCommand();
cmd2.Connection = conn2;
cmd2.CommandText = "SELECT * FROM observation WHERE day BETWEEN @fromDate AND @toDate ORDER BY day ASC, hour ASC ";
cmd2.Parameters.AddWithValue("fromDate", dateTimePicker2.Value.Date);
cmd2.Parameters.AddWithValue("toDate", dateTimePicker3.Value.Date);
SqlDataReader reader = cmd2.ExecuteReader();
DataSet ds = new DataSet();
DataTable dt = new DataTable("dateRange");
dt.Columns.Add("day");
dt.Columns.Add("hour");
dt.Columns.Add("temp");
DataRow dr = dt.NewRow();
int counter = 0;
while (reader.Read())
{
if (reader[1].ToString() != dt.TableName)
{
if (dt.Rows.Count != 0 && dt.TableName != "dateRange")
{
dt.AcceptChanges();
ds.Tables.Add(dt);
counter++;
}
dt = new DataTable(reader[1].ToString());
dt.Columns.Add("day"):
dt.Columns.Add("hour");
dt.Columns.Add("temp");
}
dr = dt.NewRow();
dr[0] = reader[2];
dr[1] = reader[3];
dt.Rows.Add(dr);
}
if (dt.Rows.Count != 0)
{
dt.AcceptChanges();
ds.Tables.Add(dt);
}
else
{
lblError.Visible = false;
}
for (int i = 0; i < counter; i++)
{
chart1.Series[i].Name = i.ToString();
chart1.Series[i].ChartType = System.Windows.Forms.DataVisualization.Charting.SeriesChartType.Line;
chart1.Series[i].BorderWidth = 5;
if (i % 2 == 0)
{
chart1.Series[i].Color = Color.Red;
}
else
{
chart1.Series[i].Color = Color.Green;
}
chart1.DataSource = ds.Tables[i];
chart1.Series[i].XValueMember = "hour";
chart1.Series[i].YValueMembers = "temp";
}
chart1.Legends[0].Alignment = StringAlignment.Center;
chart1.Legends[0].Docking = System.Windows.Forms.DataVisualization.Charting.Docking.Top;
chart1.DataBind();
chart1.Visible = true;
cmd2.Connection.Close();
Thanks!
A solution I found was to re format my dataSource. I created a DataTable with the first column being Hours and it goes from 1 to 24. the following columns are one for each day that I want to represent.
There are two Queries. the first one is to know how many days are in the interval and to create the appropriate number of Columns and Series. The second Query is the one that brings in all the Data.
Here is the Code: