列 'tempValue' 不属于 table

Column 'tempValue' does not belong to table

我目前在使用 ajax takeit in visual studio 2010 为我的饼图编码时遇到错误。我已经被困在这里将近 2 个小时,找不到任何解决方案。我已经尝试在这个论坛中搜索并尝试了一些但仍然遇到同样的问题有人可以帮忙吗?

private void BindChart()
{
    DataTable dt = new DataTable();

    string connstr = ConfigurationManager.ConnectionStrings["wkzdbConnectionString"].ConnectionString;
    SqlConnection conn = new SqlConnection(connstr);
    conn.Open();

    string query = "select count(case when tempValue < 24 then 1 end), count(case when tempValue between 24 and 30 then 1 end), count(case when tempValue > 30 then 1 end) FROM Datacentre";
    SqlDataAdapter da = new SqlDataAdapter(query, conn);

    DataSet ds = new DataSet();

    da.Fill(dt);

    string[] x = new string[] { "< 24 Degrees", "24 - 30 Degrees", "> 30 Degrees" };

    foreach (DataRow dr in dt.Rows)
    {
        PieChart1.PieChartValues.Add(new AjaxControlToolkit.PieChartValue
        {
            Category = x.ToString(),
            Data = Convert.ToDecimal(dr["tempValue"])
        }); //here is the error 'Column 'tempValue' does not belong to table'
    }
}

这是我的 table:

我的饼图是什么样子的:

我希望它看起来像:

您的代码中有一点断开。首先,您的查询没有为列命名,因此每一列的名称看起来都非常有趣。打破数据集并展开它,你就会明白我的意思。从查询开始:

string query = @"select count(case when tempValue < 24 then 1 end) as Cold,
                        count(case when tempValue between 24 and 30 then 1 end) as NotAsCold,
                        count(case when tempValue > 30 then 1 end) as Warmish
                 FROM Datacentre";

然后使用这些命名的列,您将拥有一个可以轻松获取的值。不过,我不确定您要用该饼图做什么。我会把它留给你。您可以将导致错误的行更改为:

Data = Convert.ToDecimal(dr["Cold"]);

更新 - 饼图

如我所料,生成的饼图并不是您想要的。这里有几个问题。首先让我们看看 应该 工作:

for (var i=0;i<3;i++)
{
    PieChart1.PieChartValues.Add(new AjaxControlToolkit.PieChartValue
    {
        Category = x[i],
        Data = Convert.ToInt32(dt.Rows[0][i])
    });
}

现在让我们探讨一下不同之处和原因。我们将从 foreach 迭代器开始。给定 3 个计数且没有分组的查询,不可能获得超过一行的数据,因此遍历这些行是没有意义的。

那么为什么我要将它切换到 for 循环呢? x[] 包含 3 列 headers,查询行有 3 列,每列的顺序相同。我们想要为这 3 列中的每一列保留一块馅饼。有什么比索引 for 循环更好的方法来创建这些切片?

请注意,Category 赋值现在引用 数组中的一项 ,而不是数组本身。因为它是一个字符串数组,所以我们不再需要 ToString() 方法。您之前看到的类别是因为 Array.ToString() 将 return 描述数组 object 的字符串 - 在本例中为 System.String[].

您的 SELECT 是:

select count(case when tempValue < 24 then 1 end), count(case when tempValue between 24 and 30 then 1 end), count(case when tempValue > 30 then 1 end)

它没有公开 tempValue,因此代码 dr["tempValue"] 无法读取它。