论坛中最常见的一个问题是:“ 我怎样在 datagrid 中显示列合计?”。 我亲自多次为这个问题提供了示例代码,因此,我想在do.netjunkies 的标题中提供这么一份指南。 在这份指南中你将会学到怎样在 datagrid 中编程实现对某一列的值进行统计,并在 datagrid 的页脚中显示其合计值。这份指南中供下载的示例中包括了 c# 和 visual basic.net 两种代码。
这份指南的最终结果看起来像这样:
<%@ 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> 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;
}
}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());
}
}private void calctotal(string _price)
{
try
{
runningtotal += double.parse(_price);
}
catch
{
//捕获错误
}
}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);
}
}Java Asp PHP .Net XML C/C++ CGI VB Jsp J2ee J2se J2me EJB Servlet Tomcat Resin Struts Weblogic Eclipse ANT GUI JMS Web servise IDEA Webphere Hibernate Spring Jboss Applet Swing Socket Javamail Perl Ajax P2P 安全 模式 框架 测试 开源 游戏
Windows XP Windows 2000 Windows 2003 Windows Me Windows 9.x Linux UNIX 注册表 操作系统 服务器 应用服务器