Get total of a data row asp.net

本秂侑毒 提交于 2019-12-12 05:44:39

问题


Im trying to get the values from each column in a single row to equal a total. Here is the code that im using to achieve this in c# asp.net

DataTable dt = ds.Tables.Add("InspireTable");
        string pass = (String)Session["name"];
        if (pass.Equals("High"))
        {
            dt.Columns.Add("Inspire", typeof(string));
            dt.Columns.Add("SNS", typeof(int));
            dt.Columns.Add("TT", typeof(int));
            dt.Columns.Add("Music", typeof(int));
            dt.Columns.Add("Total", typeof(string));


            DataRow row = dt.NewRow();
            row["Inspire"] = "Score";
            row["SNS"] = 10;
            row["TT"] = 10;
            row["Music"] = 0;

            dt.Rows.Add(row);
            Chart1.DataSource = dt;
            this.GridView1.Visible = true;
            GridView1.DataSource = dt;
            GridView1.DataBind();

        }

Any ideas? I have tried calling each column and adding them but that seem not to work.


回答1:


With the old DataTable.Compute method, for example:

int snsTotal = (int) dt.Compute("SUM(SNS)", null); // the second argument is the filter

Here's the "modern" Linq approach:

int snsTotal = dt.AsEnumerable().Sum(r => r.Field<int>("SNS"));

Edit: it seems as if you want to sum the numeric values of each row into a "total"-column. Then you can use a Column-Expression:

dt.Columns.Add("Total", typeof(int), "SNS + TT + Music");


来源:https://stackoverflow.com/questions/13647103/get-total-of-a-data-row-asp-net

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!