图表 COUNT 查询 C#?

Chart COUNT Query C#?

C# 有点新手,我对我在学校作业代码中遇到的这个问题有点困惑。尝试在 winform 中为学校项目制作 Room Activity 图表,其中我输入的 SQL COUNT 查询计算 Event 列下具有值 'Room Activity' 的行,但出于某种奇怪的原因,我收到一个 ArgumentException 未处理错误,告诉我未找到名称为 'Event' 的列。

我的代码哪里做错了?

using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Windows.Forms.DataVisualization.Charting;
using System.Configuration;
using System.Data.SqlClient;




namespace Database_Chart_test
{
    public partial class Form1 : Form
    {

        string strConnectionString = ConfigurationManager.ConnectionStrings["Database_Chart_test.Properties.Settings.LibrarySystemConnectionString"].ConnectionString;


        public Form1()
        {
            InitializeComponent();
        }

        private void Activitychart_Click(object sender, EventArgs e)
        {

        }

        private void RoomChart()
        {
            SqlConnection con = new SqlConnection(strConnectionString);
            DataSet ds = new DataSet();
            con.Open();
            SqlDataAdapter adapt = new SqlDataAdapter("SELECT COUNT(*) FROM Log WHERE Event = 'Room Activity'", con);
            adapt.Fill(ds);
            Activitychart.DataSource = ds;

            Activitychart.Series["WithActivity"].XValueMember = "Event";
            Activitychart.Series["WithActivity"].YValueMembers = "Event";
            con.Close();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            // TODO: This line of code loads data into the 'librarySystemDataSet1.RoomsBooking' table. You can move, or remove it, as needed.
            this.roomsBookingTableAdapter.Fill(this.librarySystemDataSet1.RoomsBooking);
            // TODO: This line of code loads data into the 'librarySystemDataSet.Log' table. You can move, or remove it, as needed.
            this.logTableAdapter.Fill(this.librarySystemDataSet.Log);
            RoomChart();
        }
    }
}

SELECT COUNT(*) FROM Log WHERE Event = 'Room Activity'执行后,会return一个1列1行(计数)的table。

查询结果:

所以 ArgumentException 的原因是 ds.Tables[0] 中没有名为 Event 的列。

如果你想得到count,只需调用ExecuteScalar Method

using (SqlConnection conn = new SqlConnection(strConnectionString))
{
    string strSQL = "SELECT COUNT(*) FROM Log WHERE Event = 'Room Activity'";
    SqlCommand cmd = new SqlCommand(strSQL, conn);

    conn.Open();
    int count = (int)cmd.ExecuteScalar();
    // add data point
    Activitychart.Series["WithActivity"].Points.AddXY("Event", count);
    Console.WriteLine("The count is {0}", count);
}

此外,根据您提供的代码,您正试图将Event(一个字符串)用作YValueMembers。这似乎不太合理。一般YValueMembers应该是数字类型。