sql显示和结果

时间:2015-01-15 11:23:46

标签: c# sql gridview

如何在以下网格视图中显示查询的总和结果:

string raf5 = string.Format("select SUM(orderDetails.unitPrice) from orderDetails INNER JOIN Orderz ON orderDetails.orderId=Orderz.Id AND Orderz.customerId={0} ", k);
SqlCommand comm5 = new SqlCommand(raf5, c);
SqlDataReader r55 = comm17.ExecuteReader();
DataTable ts = new DataTable();
ts.Columns.Add("Total Sum", typeof(string));
while (r55.Read())
{
    ts.Rows.Add(r55["unitPrice"].ToString());
}
c.Close();
GridView3.DataSource = ts;
GridView3.DataBind();

1 个答案:

答案 0 :(得分:1)

您遇到的问题是缺少列名称。 您需要为总和指定列名称,如下所示:

string raf5 = string.Format("select SUM(orderDetails.unitPrice) as unitPrice from orderDetails INNER JOIN Orderz ON orderDetails.orderId=Orderz.Id AND Orderz.customerId={0} ", k);

或者,您可以在数据读取器中按索引获取列:

ts.Rows.Add(r55[0].ToString());

此外,您返回的是单个值,因此您最好使用(decimal)com17.ExecuteScalar()