按钮重复加载相同的信息,而不是一次(C#)

时间:2018-11-11 08:55:40

标签: c# sql button bar-chart

我正在尝试将SQL Server中的数据加载到条形图上,这已经实现了,但是当我单击``加载''按钮时,该图的绘制与点击次数成正比。我希望单击一下即可加载数据仅每周一次,而其他点击则只是刷新而不会错误地绘制在其他星期上。

一键,期望的输出。Desired display

单击两次,以此类推即可刷新图形

Second clicks

Third click

等等,但我得到了这些结果。

这是加载按钮代码:

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

` 这是表格:

enter image description here

谢谢。

1 个答案:

答案 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块。