以表格形式顯示資料可以帶來很多好處。在本文中,我將講解如何使用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;