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;
}
Page_Load 呼叫 BindData() 將 DataTable 繫結至 GridView。CommandName="AddToCart"),觸發 RowCommand 事件。RowCommand 取得 CommandArgument (商品 ID),從 Session 取得購物車 DataTable,新增/更新項目後存回 Session。RowCommand 可透過 e.CommandArgument 取得主鍵值。整合金流 API (PayPal、ECPay)、訂單資料庫寫入、Email 通知、庫存扣減交易處理、優惠券/折扣邏輯。