我正在尝试将SQL Server中的数据加载到条形图上,这已经实现了,但是当我单击``加载''按钮时,该图的绘制与点击次数成正比。我希望单击一下即可加载数据仅每周一次,而其他点击则只是刷新而不会错误地绘制在其他星期上。
单击两次,以此类推即可刷新图形
等等,但我得到了这些结果。
这是加载按钮代码:
private void Load_BTN_Click_1(object sender, EventArgs e)
{
try
{
string selectQuery = "SELECT DATEADD(week, DATEDIFF(week, 0, Date), 0) AS month, SUM(Fuel_Amount) AS Expr1 FROM Fuel_Attendend GROUP BY DATEADD(week, DATEDIFF(week, 0, Date), 0)";
cmd = new SqlCommand(selectQuery, connection);
try
{
connection.Open();
dr = cmd.ExecuteReader();
while (dr.Read())
{
this.chart1.Series["Fuel_Amount"].Points.AddY(dr.GetInt32(1));
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
connection.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
` 这是表格:
谢谢。
答案 0 :(得分:1)
我建议您清除chart1系列 然后添加Fuel_Amount系列
如以下代码所示。
private void Load_BTN_Click_1(object sender, EventArgs e)
{
try
{
this.chart1.Series.Clear();
this.chart1.Series.Add("Fuel_Amount");
string selectQuery = "SELECT DATEADD(week, DATEDIFF(week, 0, Date), 0) AS month, SUM(Fuel_Amount) AS Expr1 FROM Fuel_Attendend GROUP BY DATEADD(week, DATEDIFF(week, 0, Date), 0)";
cmd = new SqlCommand(selectQuery, connection);
try
{
connection.Open();
dr = cmd.ExecuteReader();
while (dr.Read())
{
this.chart1.Series["Fuel_Amount"].Points.AddY(dr.GetInt32(1));
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
connection.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
这将使图表在单击按钮时刷新。
我还建议您在处理SqlCommand和Connection时使用Using块。