首页  ·  知识 ·  云计算
利用DataTable实现报表小计和总计
ztf704  http://hi.baidu.com/ztf704/blog/  综合  编辑:dezai  图片来源:网络
DataTable.Compute 方法 计算用来传递筛选条件的当前行上的给定表达式。

DataTable.Compute 方法

计算用来传递筛选条件的当前行上的给定表达式。
http://msdn2.microsoft.com/zh-cn/library/system.data.datatable.compute(VS.80).aspx

DataTable.DataColumn.Expression 属性

获取或设置表达式,用于筛选行、计算列中的值或创建聚合列。
http://msdn2.microsoft.com/zh-cn/library/system.data.datacolumn.expression(VS.80).aspx

DataTable and DataColumn Expressions in ADO.NET - Calculated Columns

by
David Hayden ( Florida .NET Developer )

A question came up in the MSDN forums as to how to handle Data Column Expressions within a DataTable in ADO.NET. The expression syntax available to create calculated columns is probably much richer than you might think if you don't play around a lot with the Expression Property of the DataColumn.

The question was how to create a Calculated ColumnC that had the following logic:

  • If ColumnA - ColumnB > 100, ColumnC = “Yes“, else ColumnC = “No“

We can create a DataTable to do this in only a few lines of code:

// Create the DataTable
DataTable dt = new DataTable("Expressions");

// Create ColumnA and ColumnB
DataColumn columnA =
       
new DataColumn("columnA", typeof(int));
DataColumn columnB
=
       
new DataColumn("columnB", typeof(int));

// Create ColumnC
DataColumn columnC =
       
new DataColumn("columnC", typeof(string),
       
"IIF(columnA - columnB > 100,'Yes','No')");

// Add Columns to DataTable
dt.Columns.AddRange(new DataColumn[]
                      { columnA, columnB, columnC });

// Add a Couple of Rows Supplying ColumnA and ColumnB Data...
dt.Rows.Add(new object[] { 200, 50 });
dt.Rows.Add(
new object[] { 100, 20 });

As you can see above, there is an IIF Function available to us that populates the column based on whether an expression is true or false.

IIF(expr, truepart, falsepart)

expr -- The expression to evaluate.

truepart -- The value to return if the expression is true.

falsepart -- The value to return if the expression is false.

I wrote the expression as follows:

IIF(columnA - columnB > 100,'Yes','No')

Using the DataSet Visualizer in VS2005 we can see the results of the DataColumn Expression:

Conclusion

Creating Calculated Columns in a DataTable using the DataColumn.Expression Property is really cool and the Expression Syntax available may be a lot richer than you might think. For more on the functions and operators supported by the DataColumn.Express Property, see the following documentation on MSDN.

Related ADO.NET Tutorials

Source: David Hayden ( Florida .NET Developer )

Filed: ADO.NET Tutorials

本文作者:ztf704 来源:http://hi.baidu.com/ztf704/blog/
CIO之家 www.ciozj.com 微信公众号:imciow
   
免责声明:本站转载此文章旨在分享信息,不代表对其内容的完全认同。文章来源已尽可能注明,若涉及版权问题,请及时与我们联系,我们将积极配合处理。同时,我们无法对文章内容的真实性、准确性及完整性进行完全保证,对于因文章内容而产生的任何后果,本账号不承担法律责任。转载仅出于传播目的,读者应自行对内容进行核实与判断。请谨慎参考文章信息,一切责任由读者自行承担。
延伸阅读