首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> .NET 網頁程式設計 >> ASP.NET 基礎 >> 關於ASP.NET

ASP.NET 2.0 打造購物車與付款系統(二):GridView 資料來源建構與購物介面

     編輯:關於ASP.NET

資料來源靈活建構:自由建立 DataTable

GridView 資料來源不限於資料庫,可為 XML、動態饋送、或程式碼動態建構。本範例於 Application_Start 或首次載入時動態建立 DataTable 作為商品目錄:

private DataTable CreateProductTable() {
    DataTable dt = new DataTable();
    dt.Columns.Add(new DataColumn("id", typeof(int)) { Unique = true });
    dt.Columns.Add("thumb", typeof(string));
    dt.Columns.Add("name", typeof(string));
    dt.Columns.Add("price", typeof(double));
    dt.Columns.Add("quantity", typeof(int));
    dt.PrimaryKey = new[] { dt.Columns["id"] };
    // 填入範例商品資料...
    return dt;
}

GridView 繫結與購物車互動流程

  1. Page_Load 呼叫 BindData() 將 DataTable 繫結至 GridView。
  2. GridView 內含「加入購物車」按鈕 (CommandName="AddToCart"),觸發 RowCommand 事件。
  3. RowCommand 取得 CommandArgument (商品 ID),從 Session 取得購物車 DataTable,新增/更新項目後存回 Session。
  4. 另一 GridView 顯示購物車內容,支援數量修改、移除、小計計算。

關鍵技術點

  • DataKeyNames 設定 "id",RowCommand 可透過 e.CommandArgument 取得主鍵值。
  • TemplateField 客製化購物車列:數量 TextBox、單價 Label、小計 Label、移除 LinkButton。
  • Session 儲存購物車:跨頁面保持,結帳時再持久化至資料庫。

擴充方向

整合金流 API (PayPal、ECPay)、訂單資料庫寫入、Email 通知、庫存扣減交易處理、優惠券/折扣邏輯。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved