ASP.NET數據格中計算數值總和
2024-07-10 12:57:34
供稿:網友
以表格形式顯示數據可以帶來很多好處。在本文中,我將講解如何使用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;