C# 使用DataTable时,如何对列执行计算?

C# 使用DataTable时,如何对列执行计算?,c#,winforms,datatable,C#,Winforms,Datatable,我需要计算一列的总和,并将其显示在total.Text中。我怎样才能做到这一点?此列有无限的数据,可以随时更改。我正在使用VS2010。我是C#的新手 例如: _____________________ | last_retail_price | --------------------- | 500 | | 200 | | 5.60 | --------------------- total.Text = 705

我需要计算一列的总和,并将其显示在
total.Text
中。我怎样才能做到这一点?此列有无限的数据,可以随时更改。我正在使用VS2010。我是C#的新手

例如:

_____________________
| last_retail_price |
---------------------
|      500          |
|      200          |
|      5.60         |
---------------------
total.Text = 705.6  \\ The sum of column which I need
我的代码:

private void add_click(object sender, EventArgs e) 
    SqlConnection con = new SqlConnection("Data Source=.\\SQLEXPRESS;AttachDbFilename=D:\\fuda\\Fuda.mdf;Integrated Security=True;Connect Timeout=30;User Instance=True");
    SqlDataAdapter da = new SqlDataAdapter();
    DataTable tl = new DataTable();
    da.SelectCommand = new SqlCommand("Select last_ret_prc from pur_temp", con);
    con.Open();
    da.Fill(tl);

    object sum_obj;
    sum_obj = tl.Compute("sum(last_ret_prc)");
    total.Text = sum_obj.ToString();
    con.close();
}
大概是这样的:

var con = new SqlConnection(/*your connection string*/);
var cmd = conn.CreateCommand();
cmd.CommandText = @"Select Sum(last_ret_prc) FROM pur_temp GROUP BY last_ret_prc";
string sum_obj = cmd.ExecuteScalar().ToString();

total.Text = sum_obj;

con.Dispose();
现在SQL查询只返回一个值。
上一次更新prc的总和

方法
ExecuteScaler()
返回第一行第一列中的第一个值。

目前,您的代码永远不会工作:

  • 列名是last_retail_price,但您在代码中使用了last_ret_prc
  • con.close应该是con.close()
  • Compute接受两个参数“expression”和“filter”。您仍然需要提供第二个参数,即使它为null
我已经清理了代码并在本地进行了测试,它运行良好:

SqlConnection con =
    new SqlConnection(
        @"Data Source=.\SQLEXPRESS;AttachDbFilename=D:\fuda\Fuda.mdf;Integrated Security=True;Connect Timeout=30;User Instance=True");
SqlDataAdapter da = new SqlDataAdapter();
DataTable tl = new DataTable();
da.SelectCommand = new SqlCommand("Select last_retail_price from pur_temp", con);
con.Open();
da.Fill(tl);

object sum_obj = tl.Compute("sum(last_retail_price)", null);
total.Text = sum_obj.ToString();
con.Close();
或者,如果您只想显示总数,最好使用一个SqlCommand:

con.Open();
var command = new SqlCommand("SELECT SUM(last_retail_price) FROM pur_temp", con);
var result = command.ExecuteScalar();
total.Text = result.ToString();
con.Close();

在这里,它给我以下行对象sum_obj=tl.Compute(“sum(last_retail_price)”,null)中的错误\\聚合函数Sum()和类型:String的用法无效。以上所有编码中都存在相同的错误,甚至我的也是如此……数据库中的最后一个零售价必须是数字类型-十进制(18,2)。我怀疑您当前正在存储字符串(char/nchar/varchar/nvarchar)?错误表明您正在尝试对字符串求和-求和(500、200、5.60)有效,而求和(“500”、“200”、“5.60”)无效。我有另一个想法,您可以帮助我这样想:int a=column1&row 1,int 2=column1&row 2,int 3=第1列和第3行,依此类推至少20我是指相同的列但不同的行,然后将所有int相加,如total.text=1+2+3+4+5…..20是否可能?我在这里使用VarChar(Max)作为数据表中的最后一个返回prc,这是错误的。非常感谢你们两位