aspx文件
<%@ Page Inherits="myApp.calcTotals" Src="" %>
<!--自己改一下src-->
<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">
<!--在footer中显示合计-->
<Columns>
<asp:BoundColumn HeaderText="Title" DataField="title" />
<asp:BoundColumn HeaderText="Price" DataField="price"
ItemStyle-HorizontalAlign="Right"
HeaderStyle-HorizontalAlign="Center" />
</Columns>
</asp:DataGrid>
</body>
</html>
下面给出vb.net和C#两种代码
vb.net
Imports System
Imports System.Web
Imports System.Web.UI
Imports System.Web.UI.WebControls
Imports System.Web.UI.HtmlControls
Imports System.Data
Imports System.Data.SqlClient
Namespace myApp
Public Class calcTotals : Inherits Page
Protected MyGrid As DataGrid
Private runningTotal As double = 0
'定义合计变量
Private Sub CalcTotal(_price As String)
'求和
Try
runningTotal += Double.Parse(_price)
Catch
' 空值
End Try
End Sub
Public Sub MyDataGrid_ItemDataBound(sender As Object, e As DataGridItemEventArgs)
If e.Item.ItemType = ListItemType.Item Or e.Item.ItemType = ListItemType.AlternatingItem Then
CalcTotal( e.Item.Cells(1).Text )
'循环执行求和程序
e.Item.Cells(1).Text = string.Format("{0:c}", Convert.ToDouble(e.Item.Cells(1).Text))
Elseif(e.Item.ItemType = ListItemType.Footer )
e.Item.Cells(0).Text="Total"
e.Item.Cells(1).Text = string.Format("{0:c}", runningTotal)
End If
End Sub
Protected Sub Page_Load(sender As object, e As EventArgs)
Dim myConnection As New SqlConnection("server=Localhost;database=pubs;uid=sa;pwd=")
Dim myCommand As New SqlCommand("SELECT title, price FROM Titles WHERE