ASP.NET数据格中计算数值总和

      以表格形式显示数据可以带来很多好处。在本文中,我将讲解如何使用DataGrid计算总计,这在处理数值时会经常用到。

     在讨论DataGrid控制时,常常可以听到别人对此方法的嘲笑。他们常常抛弃它转而使用第三方的工具。事实上,DataGrid作为. NET Framework的核心部分,已成为我开发工具箱中极具价值的工具。

什么是总计?

在应用程序中使用DataGrid控制可以允许你以对绝大部分用户来说熟悉的格式来发布数据(栅格格式常常被用于如微软Excel等电子数据表格应用程序)。使用此类型的应用程序,用户可以按照习惯查看自定义函数如每栏总计、平均值等。而这些函数并不是DataGrid的标准函数,你可以自行编写代码来轻松地实现这些函数。

在本例中,我将使用所有SQL Server版本都可提供的Northwind范例数据库,并从顺序表格中提取数据。我将对货物栏计算总计值,这个总计值应当在DataGrid中一致地显示出来。一下就是此应用程序的C#代码。

 

<% @ Import Namespace = " System.Data.SqlClient "   %>

<% @ Import Namespace = " System.Data "   %>

<% @ Page language = " c# "   %>

<! DOCTYPE HTML PUBLIC  " -//W3C//DTD HTML 4.0 Transitional//EN "   >

< HTML >< HEAD >< title > Builder.com DataGrid Totals Example </ title >

</ HEAD >

< body MS_POSITIONING = " GridLayout " >

double  totalFreight  =   0 ;

private   void  Page_Load( object  sender, System.EventArgs e)  {

if (!Page.IsPostBack) {

BindData();

}
 }


private   void  BindData()  {

const string sConn;

sConn 
= "server=(local);Initial Catalog=Northwind;UID=ctester;PWD=password";

try {

SqlConnection conn 
= new SqlConnection(sConn);

conn.Open();

string sSQL = "SELECT TOP 10 OrderID, Freight, ShipName, ShipCountry FROM

 Orders
";

SqlCommand comm 
= new SqlCommand(sSQL, conn);

SqlDataReader dr 
= comm.ExecuteReader();

dgNorthwind.DataSource 
= dr;

dgNorthwind.DataBind();

}
 catch (Exception e) {

Console.WriteLine(e.ToString());

}
 }


private   void  doTotal( object  sender, DataGridItemEventArgs e)  {

if (e.Item.ItemType == ListItemType.Item | e.Item.ItemType ==

 ListItemType.AlternatingItem) 
{

double currentFreight = Convert.ToDouble(DataBinder._Eval(e.Item.DataItem,

 
"Freight"));

totalFreight 
+= currentFreight;

}
 else if (e.Item.ItemType == ListItemType.Footer) {

e.Item.Cells[
2].Text = "Total:";

e.Item.Cells[
3].Text = Convert.ToString(totalFreight);

}
 }


</ script >

< form id = " frmDataGridTotals "  method = " post "  runat = " server " >

< asp:DataGrid id = " dgNorthwind "

style
= " Z-INDEX: 101; LEFT: 24px; POSITION: absolute; TOP: 32px "

runat
= " server "  Height = " 320px "  Width = " 496px "

AutoGenerateColumns
= " False "

onfiltered
= " doTotal "

ShowFooter
= " True "  CellPadding = " 4 "  CellSpacing = " 0 "

BorderStyle
= " Solid "  BorderWidth = " 1 "  Gridlines = " None "

BorderColor
= " Black "

ItemStyle
- Font - Name = " Verdana "

ItemStyle
- Font - Size = " 9pt "

HeaderStyle
- Font - Name = " Verdana "

HeaderStyle
- Font - Size = " 10pt "

HeaderStyle
- Font - Bold = " True "

HeaderStyle
- ForeColor = " White "

HeaderStyle
- BackColor = " Gray "

FooterStyle
- Font - Name = " Verdana "

FooterStyle
- Font - Size = " 10pt "

FooterStyle
- Font - Bold = " True "

FooterStyle
- ForeColor = " Red "

FooterStyle
- BackColor = " Gray " >

< Columns >

< asp:BoundColumn DataField = " OrderID "  HeaderText = " # "  ItemStyle - Width = " 10% "

 HeaderStyle
- HorizontalAlign = " Center "   />

< asp:BoundColumn DataField = " ShipName "  HeaderText = " Customer "  ItemStyle

- Width = " 50% "   />

< asp:BoundColumn DataField = " ShipCountry "  HeaderText = " Country "  ItemStyle

- Width = " 20% "   />

< asp:BoundColumn DataField = " Freight "  HeaderText = " Freight "  ItemStyle - Width = " 20% "

 
/>

</ Columns ></ asp:DataGrid >

</ form ></ body ></ HTML >  

或许首先你注意到的是此页面没有使用code-behind特性。所有的代码都放在aspx文件中。页面首部必需的import指令保证了数据交互所需代码的可用性。页面事件Page_Load调用了BindData方法,这正是与数据库交互的地方。它连接到数据库并创建SqlDataReader对象,此对象包含了由SQL语句返回的记录。对象SqlDataReader通过对象DataGrid的DataSource属性把DataGrid对象放入页面中。对象DataGrid的DataBind方法负责装入数据。DataGrid的HTML定义了栏目及其格式,包括颜色、字体、对齐等。

DataBind方法还保持着对来自数据源的数据栏的动态求和。以下代码返回一行数据的详细个数:

double currentFreight = Convert.ToDouble(DataBinder._Eval(e.Item.DataItem,

 "Freight"));

此行代码返回由_Eval语句获得的值,并将其转换为保持动态求和所必需的格式。一旦返回了此值,它将被加到total变量中。在DataGrid中的每行都将进行此操作。以下代码定义了一行:

if(e.Item.ItemType==ListItemType.Item |

e.Item.ItemType==ListItemType.AlternatingItem)

此语句对于DataGrid中的每行都返回true。语句的其他部分决定了何时显示总计数量。当所有的行(if语句的第一部分为false)都被处理时该语句被执行,除非以以下语句开头:

else if (e.Item.ItemType == ListItemType.Footer)

当到达页脚时,此语句将返回true。既然我们对页眉没有兴趣,我们必须确定这是否是页脚。在这种情况下,总计值将显示在DataGrid合适的栏中。必须记住栏的编号是从0开始。由此,我们得出栏2和栏3,而不是栏3和栏4。你可以通过用Item的索引值来覆盖Cells属性中的Text属性来完成此工作。

e.Item.Cells[2].Text = "Total:";

e.Item.Cells[3].Text = Convert.ToString(totalFreight);

需要注意总计值在显示前被转换为字符串值。

另一种方法

当并不急需获得数据的总计值时,你可以使用另外一种方法。此方法通过SQL SUM命令来计算栏中数值的总数。这种方法的缺点在于它需要一个单独的数据库调用,并且结果必须存放在DataSet或其他类似的对象中。

翻页

你或许想知道DataGrid 翻页是如何影响到总计值的。本文中的范例代码将显示对屏幕所示的数据的求和,所以对每页来说结果都会不同(你必须调整代码以保持对每个变量的求和,但这已经超出了本文所讨论的范围)。

由于你不能使用SqlDataReader来翻页,本文的代码将不能用于翻页的情况。但你可以将代码修改为使用DataSet对象以利用其提供的翻页选项。以下代码改变将完成此工作:

SqlCommand comm = new SqlCommand(sSQL, conn);

SqlDataAdapter da = new SqlDataAdapter();

da.SelectCommand = comm;

DataSet ds = new DataSet();

da.Fill(ds);

dgNorthwind.DataSource = ds;


版权声明:本文为bulbul2006原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。