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>
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;
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); } }
protected void Page_Load(object sender, EventArgs e) { SqlConnection myConnection = new SqlConnection("server=Localhost;database=pubs;uid=sa;pwd=;"); SqlCommand myCommand = new SqlCommand("SELECT title, price FROM Titles WHERE price > 0", myConnection);
try { myConnection.Open(); MyGrid.DataSource = myCommand.ExecuteReader(); MyGrid.DataBind(); myConnection.Close(); } catch(Exception ex) { HttpContext.Current.Response.Write(ex.ToString()); } } }
|