<%@ Page Inherits="myApp.calcTotals" Src="20010731T0101.aspx.cs" %> |
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"> |
ItemStyle-HorizontalAlign="Right" HeaderStyle-HorizontalAlign="Center" /> |
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); } } |