天天看點

在DataGrid中添加一個合計字段

 

在DataGrid中添加一個合計字段

翻譯:[email protected]

你是否花了很時間來閱讀 ASPNG 清單?如果不是的話,我非常推薦它。你可以通路

http://www.asp.net 或 http://www.asplists.com。最近的最常見的一個問題是:“ 我怎樣在 DataGrid 中顯示列合計?”。 我親自多次為這個問題提供了示例代碼,是以,我想在DotNetJunkies 的标題中提供這麼一份指南。 在這份指南中你将會學到怎樣在 DataGrid 中程式設計實作對某一列的值進行統計,并在 DataGrid 的頁腳中顯示其合計值。這份指南中供下載下傳的示例中包括了 C# 和 Visual Basic.NET 兩種代碼。

這份指南的最終結果看起來像這樣:

在DataGrid中添加一個合計字段

從上圖可看出:

上面所用到的螢幕圖檔中的 DataGrid 是一個非常典型的 DataGrid 。有許多控制 DataGrid 外觀的屬性,它使用兩個 BoundColumns 來操作資料,但這并不是最重要的。做好這項工作真正重要的是使用 DataGrid.OnItemDataBound 事件。這個事件将會觸發每次綁定一條記錄到 DataGrid。你可以為這個事件建立一個事件處理,以操作資料記錄。在這種情況下,你将會得到運作時 Price 列的合計值。

頁腳指的是資料範圍的最後一行。當這行被限定時,在事件句處理你可以得到 Price 列的運作時統計值。

實施:

首先讓我們找到一種方法來操作 Web 窗體輸出。 這份指南中,你将使用一個 Web 窗體 (calcTotals.aspx) 以及一個類代碼檔案 (calcTotals.aspx.cs)。這份指南的意圖是, 類代碼将會使用 Just-In-Time 編譯器來編譯。 這裡是 calcTotals.aspx 的代碼:

<%@ Page Inherits="myApp.calcTotals" Src="20010731T0101.aspx.cs" %>

<html>

<body bgcolor="white">

<asp:DataGrid id="MyGrid" runat="server"

  AutoGenerateColumns="False"

  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="Blue"

  FooterStyle-Font-Name="Verdana"

  FooterStyle-Font-Size="10pt"

  FooterStyle-Font-Bold="True"

  FooterStyle-ForeColor="White"

  FooterStyle-BackColor="Blue"

  OnItemDataBound="MyDataGrid_ItemDataBound"

  ShowFooter="True">

  <Columns>

    <asp:BoundColumn HeaderText="Title" DataField="title" />

    <asp:BoundColumn HeaderText="Price" DataField="price"

      ItemStyle-HorizontalAlign="Right"

      HeaderStyle-HorizontalAlign="Center" />

   </Columns>

</asp:DataGrid>

</body>

</html>

在 Web 窗體中你使用 @ Page 來直接聲明這個頁所繼承的類代碼。SRC 屬性指明了類代碼将使用 JIT 編譯器來編譯。 Web 窗體中的大部分代碼樣式聲明用來使 DataGrid 外觀變得更好看。

最後指定的屬性之一是 OnItemDataBound 屬性。這個事件将會在 OnItemDataBound 事件發生時被觸發。

Web 窗體中的 DataGrid (MyGrid) 包含有兩個 BoundColumns,一個是 Title ,另一個是Price。 這裡将顯示 Pubs 資料庫(SQL Server)中 Titles 表的 title 及 price 列。

忽略代碼的定義

類代碼在所有的地方都将使用。在類代碼中,你可以操作兩個事件:Page_Load 事件以及 MyGrid_OnItemDataBound 事件。還有一個私有方法 CalcTotal, 用它來簡單的完成運作時統計的數學運算。

類代碼基本結構塊的起始部分:

using System;

using System.Web;

using System.Web.UI;

using System.Web.UI.WebControls;

using System.Web.UI.HtmlControls;

using System.Data;

using System.Data.SqlClient;

namespace myApp

{

  public class calcTotals : Page

  {

    protected DataGrid MyGrid;

    private double runningTotal = 0;

  }

}

在類代碼的基本結構中,你必須使用相關語句導入名字空間(namespace)。在類聲明中,你聲明了兩個變量,一個是類代碼中映射 Web 窗體的 DataGrid(MyGrid)控件的變量;一個是用來操作 DataGrid 的 Price 列中運作時統計的雙精度值。  Page_Load 事件 在 Page_Load 事件中,你所要做的就是連接配接到 SQL Server 并執行一個簡單的 SqlCommand。 你取得了所有 Price 值>0 的 title 和 price 資料。你使用 SqlCommand.ExecuteReader 方法傳回一個 SqlDataReader 并将其直接綁定到 DataGrid (MyGrid)。

protected void Page_Load(object sender, EventArgs e)

{

  SqlConnection myConnection = new SqlConnection("server=Localhost;database=pubs;uid=sa;pwd=;");//建立SQL連接配接

  SqlCommand myCommand = new SqlCommand("SELECT title, price FROM Titles WHERE price > 0", myConnection);//建立SQL指令

  try

  {

    myConnection.Open();//打開資料庫連接配接

    MyGrid.DataSource = myCommand.ExecuteReader();//指定 DataGrid 的資料源

    MyGrid.DataBind();//綁定資料到 DataGrid

    myConnection.Close();//關閉資料連接配接

  }

  catch(Exception ex)

  {

    //捕獲錯誤

    HttpContext.Current.Response.Write(ex.ToString());

  }

}

CalcTotals 方法

CalcTotals 方法用來處理 runningTotal 變量。這個值将以字元串形式來傳遞。 你需要将它解析為雙精度型,然後 runningTotal 變量就成了雙精度類型。

private void CalcTotal(string _price)

{

  try

  {

    runningTotal += Double.Parse(_price);

  }

  catch

  {

     //捕獲錯誤

  }

}

MyGrid_ItemDataBound 事件

MyGrid_ItemDataBound 事件在資料源中每行綁定到 DataGrid 時被調用。在這個事件進行中,你可以處理每一行資料。 這裡你的目的是,你将需要調用 CalcTotals 方法并從 Price 列傳遞文本,并用金額型格式化每一行的 Price 列, 并在頁腳行中顯示 runningTotal 的值。

public void MyDataGrid_ItemDataBound(object sender, DataGridItemEventArgs e)

{

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

  {

    CalcTotal( e.Item.Cells[1].Text );

    e.Item.Cells[1].Text = string.Format("{0:c}", Convert.ToDouble(e.Item.Cells[1].Text));

  }

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

  {

    e.Item.Cells[0].Text="Total";

    e.Item.Cells[1].Text = string.Format("{0:c}", runningTotal);

  }

}

在 MyGrid_ItemDataBound 事件句柄中,首先你得使用 ListItemType 判斷目前的 DataGridItem 是一個資料項還是AlternatingItem 行。如果是資料項,你調用 CalcTotals,并将 Price 列的值作為參數傳遞給它;然後你以金額格式對 Price 列進行格式化及着色。

如果 DataGridItem 是頁腳,可以用金額格式顯示 runningTotal。

總結 在這份指南中,你學到了怎樣使用 DataGrid.OnItemDataBound 事件來實作運作時對DataGrid 的某一列進行統計。使用這個事件,你可以建立一個列的合計并可對DataGrid行的頁腳進行着色。

繼續閱讀