开发者

Using Aggregate functions in DataView filters

i have a DataTable that has a column ("Profit"). What i want is to get the Sum of all the values in this table. I tried to do this in the following manner...

DataTable dsTemp = new DataTable();

dsTemp.Columns.Add("Profit");

DataRow dr = null;

dr = dsTemp.NewRow();
dr["Profit"] = 100;
dsTemp.Rows.Add(dr);

dr = dsTemp.NewRow();
d开发者_如何学Gor["Profit"] = 200;
dsTemp.Rows.Add(dr);

DataView dvTotal = dsTemp.DefaultView;
dvTotal.RowFilter = " SUM ( Profit ) ";

DataTable dt = dvTotal.ToTable();

But i get an error while applying the filter... how can i get the Sum of the Profit column in a variable

thank you...


Set the datacolumn to a numeric type (int, decimal, whatever):

DataColumn col = new DataColumn("Profit", typeof(int));
dsTemp.Columns.Add(col);

Use Compute:

int total = dsTemp.Compute("Sum(Profit)", "");

Note that aggregation is not a type of filter, which is the main problem with the approach you are tyring.


I used the DataTable's Compute method as suggested, and it works fine. I apply the same filtering as I use for the DataView (which is used to display the sorted and filtered data in the data grid) together with an aggregate function.

string SingleVocheridSale ="1";

 DataView view = new DataView(dt);
 view.RowFilter = string.Format("VOCHID='" + SingleVocheridSale + "'");
 dataGridview1.DataSource = view;
 object sumObject;
 sumObject = dt.Compute("Sum(NETAMT)", view.RowFilter);
 lable1.Text = sumObject.ToString();
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜