|    
         
        
          
          
            |   | 
            
   
     
        สร้างระบบ Shopping Cart ด้วย ASP.NET แบบง่าย ๆ Step by Step (VB.NET ,C#)       | 
   
 
			
			 | 
           
           
            |   | 
             
			
			
			
               
 สร้าง Shopping Cart ด้วย ASP.NET แบบง่าย ๆ Step by Step ตัวอย่างการสร้างระบบตะกร้าสั่งซื้อหรือ Shopping Cart ของ Web App (ASP.NET) บทความหาอ่านและดูได้ยากมาก เพราะเว็บที่เป็นระบบซื้อขายจะใช้ ASP.NET น้อยมาก และการเขียนก็ค่อนข้างเขียนยากและ Advanced นิดหนึ่ง ซึ่งบทความนี้ผมเองก็ใช้เวลาเขียนไม่ตำกว่า 4 ชม เพราะมีตัวอย่างทั้ง VB.NET และ C#  แต่เขียน .NET ยอมรับว่าสนุกจริง ๆ เพราะมันมี Tools และ Control เครื่องมือให้เลือกใช้ และ Event รวมทั้ง Property ต่าง ๆ มากมายให้เลือกใช้ ตัวอย่างนี้ได้เลือกใช้รูปแบบการ SELECT / INSERT หลายรูปแบบ เช่น แบบ SQL Statement หรือแบบผ่าน Parameter ทั้งนี้เพื่อต้องการให้ดูเป็นตัวอย่างในการใช้งาน  
 
อธิบายเลยแล้วกัน สำหรับตัวอย่างนี้จะใช้การเก็บรายการสั่งซื้อชั่วคราวลงใน DataTable ซึ่งจะใช้ Session จัดเก็บ DataTable อีกที และเมื่อลูกค้ายืนยันข้อมูลการสั่งซื้อ ค่อยจัดเก็บลงในฐานข้อมูลจริง ๆ ซึ่งในตัวอย่างจะใช้ Database Access หรือถ้าหากจะนำไปใช้กับ MySQL , Oracle , SQL Server ก็สามารถทำได้เช่นเดียวกัน เพียงแต่เปลี่ยนแค่ Connection String เท่านั้น และโดยหลัก ๆ แล้วในตัวอย่างนี้ ก็จะมี Screen อยู่ 3 หน้าคือ หน้าสินค้า , หน้าสั่งซื้อ , หน้าแสดงข้อมูลการสั่งซื้อ และ Code ตัวอย่างนี้ก็อ่านได้ง่ายสามารถศึกษาได้ไม่ยากเช่นเดียวกัน 
 
Screenshot 
 
  
 
คุณสมบัติและความสามารถของตัวอย่างนี้ 
- แสดงรายละเอียดสินค้าจากฐานข้อมูล Access Database 
- จัดเก็บข้อมูลการสั่งซื้อในรูปแบบ DataTable และ Session 
- หน้าจอสำหรับ Checkout 
- หน้าจอแสดงรายละเอียดการสั่งซื้อ 
 
ตารางประกอบด้วย 3 ตารางคือ 
- product 
- orders 
- orders_detail  
 
โครงสร้างตาราง product เก็บรายละเอียดสินค้า 
 
  
 
โครงสร้างตาราง orders เก็บข้อมูลลูกค้าที่สั่งซื้อ และหมายเลข OrderID 
 
  
 
โครงสร้างตาราง orders_detail เก็บรายละเอียดของแต่ล่ะ OrderID 
 
  
 
 
เริ่มต้นสร้าง Project 
 
 
  
 
เลือกเป็น ASP.NET Web Application สำหรับภาษาก็แล้วแต่ถนัด อาจจะเป็น VB.NET หรือ C# 
 
 
  
 
สำหรับฐานข้อมูลใช้ Microsoft Access ชื่อฐานข้อมูลว่า mydatabase.mdb จัดเก็บไว้ในโฟเดอร์ App_Data (สามารถดาวน์โหลดได้จากข้างล่าง) 
 
 
  
 
โครงสร้างของ Database เมื่อดูบน Server Explorer 
 
 
 
Screen Webpage ประกอบด้วย 3 ตัวคือ Product.aspx , ViewCart.aspx , ViewOrders.aspx 
 
 
  
 
Screen หน้าจอ Product.aspx  
 
 
  
 
Screen หน้าจอ ViewCart.aspx 
 
 
  
 
Screen หน้าจอ ViewOrders.aspx 
 
สำหรับ Code ทั้งหมดดาวน์โหลดได้จากข้างล่าง 
 
 
 
Code สำหรับภาษา VB.NET 
 
Product.aspx.vb 
Imports System.Data
Imports System.Data.OleDb
Partial Public Class Product
    Inherits System.Web.UI.Page
    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        BindData()
    End Sub
    Protected Sub BindData()
        Dim objConn As OleDbConnection
        Dim objCmd As OleDbCommand
        Dim strConnString As String
        strConnString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=|DataDirectory|\database.mdb"
        objConn = New OleDbConnection(strConnString)
        objConn.Open()
        Dim strSQL As String
        strSQL = "SELECT * FROM product "
        Dim dtReader As OleDbDataReader
        objCmd = New OleDbCommand(strSQL, objConn)
        dtReader = objCmd.ExecuteReader()
        myGridView.DataSource = dtReader
        myGridView.DataBind()
        dtReader.Close()
        dtReader = Nothing
        objConn.Close()
        objConn = Nothing
    End Sub
    Protected Sub myGridView_RowCommand(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewCommandEventArgs) Handles myGridView.RowCommand
        If e.CommandName = "Add2Cart" Then
            Dim strProductID As String = e.CommandArgument
            Dim dt As DataTable
            Dim dr As DataRow
            If IsNothing(Session("myCart")) Then
                dt = New DataTable()
                dt.Columns.Add("ProductID")
                dt.Columns.Add("Qty")
                Session("myCart") = dt
            End If
            dt = DirectCast(Session("myCart"), DataTable)
            Dim foundRows() As DataRow
            foundRows = dt.Select("ProductID = '" & strProductID & "'")
            If foundRows.Length = 0 Then
                dr = dt.NewRow()
                dr("ProductID") = strProductID
                dr("Qty") = 1
                dt.Rows.Add(dr)
            Else
                Dim updateRow() As DataRow
                updateRow = dt.Select("ProductID = '" & strProductID & "'")
                updateRow(0)("Qty") = updateRow(0)("Qty") + 1
            End If
            Session("myCart") = dt
            Response.Redirect("ViewCart.aspx")
        End If
    End Sub
    Protected Sub myGridView_RowDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles myGridView.RowDataBound
        If e.Row.RowType = DataControlRowType.DataRow Then
            '*** Picture ***'
            Dim imgPicture As Image = DirectCast(e.Row.FindControl("imgPicture"), Image)
            If Not IsNothing(imgPicture) Then
                imgPicture.ImageUrl = "img/" & e.Row.DataItem("Picture")
            End If
            '*** ProductID ***'
            Dim lblProductID As Label = DirectCast(e.Row.FindControl("lblProductID"), Label)
            If Not IsNothing(lblProductID) Then
                lblProductID.Text = e.Row.DataItem("ProductID")
            End If
            '*** ProductName ***'
            Dim lblProductName As Label = DirectCast(e.Row.FindControl("lblProductName"), Label)
            If Not IsNothing(lblProductName) Then
                lblProductName.Text = e.Row.DataItem("ProductName")
            End If
            '*** Price ***'
            Dim lblPrice As Label = DirectCast(e.Row.FindControl("lblPrice"), Label)
            If Not IsNothing(lblPrice) Then
                lblPrice.Text = e.Row.DataItem("Price")
            End If
            '*** AddToCart ***'
            Dim lnkAddToCart As LinkButton = DirectCast(e.Row.FindControl("lnkAddToCart"), LinkButton)
            If Not IsNothing(lnkAddToCart) Then
                lnkAddToCart.Text = "Add"
                lnkAddToCart.CommandName = "Add2Cart"
                lnkAddToCart.CommandArgument = e.Row.DataItem("ProductID")
            End If
        End If
    End Sub
End Class
 
 
ViewCart.aspx.vb 
Imports System.Data
Imports System.Data.OleDb
Partial Public Class ViewCart
    Inherits System.Web.UI.Page
    Protected strTotal As Double = 0
    Protected strSumTotal As Double = 0
    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        BindGird()
        Me.lblSumTotal.Text = "Total Amount : " & FormatNumber(strSumTotal, 2)
    End Sub
    Protected Sub BindGird()
        Dim dt As DataTable = DirectCast(Session("myCart"), DataTable)
        Me.myGridView.DataSource = dt
        Me.myGridView.DataBind()
    End Sub
    Protected Sub myGridView_RowCommand(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewCommandEventArgs) Handles myGridView.RowCommand
        If e.CommandName = "Del" Then
            Dim RowsID As Integer = e.CommandArgument
            Dim dt As DataTable
            dt = DirectCast(Session("myCart"), DataTable)
            dt.Rows(RowsID).Delete()
            Session("myCart") = dt
            Response.Redirect("ViewCart.aspx")
        End If
    End Sub
    Protected Function getProductDet(ByVal strProductID As String) As DataTable
        Dim objConn As New OleDbConnection
        Dim dtAdapter As OleDbDataAdapter
        Dim dt As New DataTable
        Dim strConnString As String
        strConnString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=|DataDirectory|\database.mdb"
        objConn = New OleDbConnection(strConnString)
        objConn.Open()
        Dim strSQL As New StringBuilder
        strSQL.Append(" SELECT * FROM product ")
        strSQL.Append(" WHERE ProductID = " & strProductID & " ")
        dtAdapter = New OleDbDataAdapter(strSQL.ToString(), objConn)
        dtAdapter.Fill(dt)
        dtAdapter = Nothing
        objConn.Close()
        objConn = Nothing
        Return dt
    End Function
    Protected Sub myGridView_RowDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles myGridView.RowDataBound
        If e.Row.RowType = DataControlRowType.DataRow Then
            '*** ProductID ***'
            Dim lblProductID As Label = DirectCast(e.Row.FindControl("lblProductID"), Label)
            If Not IsNothing(lblProductID) Then
                lblProductID.Text = e.Row.DataItem("ProductID")
            End If
            Dim dt As DataTable = getProductDet(e.Row.DataItem("ProductID"))
            '*** ProductName ***'
            Dim lblProductName As Label = DirectCast(e.Row.FindControl("lblProductName"), Label)
            If Not IsNothing(lblProductName) Then
                lblProductName.Text = dt.Rows(0)("ProductName")
            End If
            '*** Price ***'
            Dim lblPrice As Label = DirectCast(e.Row.FindControl("lblPrice"), Label)
            If Not IsNothing(lblPrice) Then
                lblPrice.Text = dt.Rows(0)("Price")
            End If
            '*** Qty ***'
            Dim lblQty As Label = DirectCast(e.Row.FindControl("lblQty"), Label)
            If Not IsNothing(lblQty) Then
                lblQty.Text = e.Row.DataItem("Qty")
            End If
            '*** Total ***'
            Dim lblTotal As Label = DirectCast(e.Row.FindControl("lblTotal"), Label)
            If Not IsNothing(lblTotal) Then
                strTotal = CDbl(e.Row.DataItem("Qty")) * CDbl(dt.Rows(0)("Price"))
                strSumTotal = CDbl(strSumTotal) + strTotal
                lblTotal.Text = FormatNumber(strTotal, 2)
            End If
            '*** Delete ***'
            Dim lnkDelete As LinkButton = DirectCast(e.Row.FindControl("lnkDelete"), LinkButton)
            If Not IsNothing(lnkDelete) Then
                lnkDelete.Text = "Delete"
                lnkDelete.CommandName = "Del"
                lnkDelete.CommandArgument = e.Row.RowIndex
                lnkDelete.Attributes.Add("OnClick", "return confirm('Delete this row?');")
            End If
        End If
    End Sub
    Protected Sub lnkClearCart_Click(ByVal sender As Object, ByVal e As EventArgs) Handles lnkClearCart.Click
        Session.Abandon()
        Response.Redirect("ViewCart.aspx")
    End Sub
    Protected Sub lnkCheckOut_Click(ByVal sender As Object, ByVal e As EventArgs) Handles lnkCheckOut.Click
        Dim dt As DataTable = DirectCast(Session("myCart"), DataTable)
        If Not IsNothing(Session("myCart")) Then
            If dt.Rows.Count > 0 Then
                Me.pnlCheckOut.Visible = True
            End If
        End If
    End Sub
    Protected Sub btnSave_Click(ByVal sender As Object, ByVal e As EventArgs) Handles btnSave.Click
        Dim objConn As New OleDbConnection
        Dim strConnString As String
        Dim strSQL As String
        Dim dtAdapter As OleDbDataAdapter
        Dim dt1 As New DataTable
        Dim dt2 As DataTable
        Dim strOrderID As String = 0
        Dim i As Integer
        strConnString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=|DataDirectory|\database.mdb"
        objConn.ConnectionString = strConnString
        objConn.Open()
        '*** Insert to orders ***'
        strSQL = "INSERT INTO orders (OrderDate,Name,Address,Tel,Email) " & _
        " VALUES " & _
        " (@sOrderDate,@sName,@sAddress,@sTel,@sEmail)"
        Dim objCmd As New OleDbCommand(strSQL, objConn)
        objCmd.Parameters.Add("@sOrderDate", OleDbType.Date).Value = Now()
        objCmd.Parameters.Add("@sName", OleDbType.VarChar).Value = Me.txtName.Text
        objCmd.Parameters.Add("@sAddress", OleDbType.VarChar).Value = Me.txtAddress.Text
        objCmd.Parameters.Add("@sTel", OleDbType.VarChar).Value = Me.txtTel.Text
        objCmd.Parameters.Add("@sEmail", OleDbType.VarChar).Value = Me.txtEmail.Text
        objCmd.ExecuteNonQuery()
        '*** Select OrderID ***'
        strSQL = "SELECT Max(OrderID) As sOrderID FROM orders "
        dtAdapter = New OleDbDataAdapter(strSQL.ToString(), objConn)
        dtAdapter.Fill(dt1)
        If dt1.Rows.Count > 0 Then
            strOrderID = dt1.Rows(0)("sOrderID")
        End If
        '*** Insert to orders_detail ***'
        dt2 = DirectCast(Session("myCart"), DataTable)
        For i = 0 To dt2.Rows.Count - 1
            strSQL = "INSERT INTO orders_detail (OrderID,ProductID,Qty) " & _
            " VALUES " & _
            " ('" & strOrderID & "','" & dt2.Rows(i)("ProductID") & "','" & dt2.Rows(i)("Qty") & "')"
            With objCmd
                .Connection = objConn
                .CommandText = strSQL
                .CommandType = CommandType.Text
                .ExecuteNonQuery()
            End With
        Next
        objConn.Close()
        objConn = Nothing
        Session.Abandon()
        Response.Redirect("ViewOrders.aspx?OrderID=" & strOrderID)
    End Sub
End Class
 
 
ViewOrders.aspx.vb 
Imports System.Data
Imports System.Data.OleDb
Partial Public Class ViewOrders
    Inherits System.Web.UI.Page
    Protected strOrderID As String = HttpContext.Current.Request.QueryString("OrderID")
    Protected strTotal As Double = 0
    Protected strSumTotal As Double = 0
    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        BindCustomer()
        BindOrderDetails()
        Me.lblSumTotal.Text = "Total Amount : " & FormatNumber(strSumTotal, 2)
    End Sub
    Protected Sub BindCustomer()
        Dim objConn As New OleDbConnection
        Dim dtAdapter As OleDbDataAdapter
        Dim dt As New DataTable
        Dim strConnString As String
        strConnString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=|DataDirectory|\database.mdb"
        objConn = New OleDbConnection(strConnString)
        objConn.Open()
        Dim strSQL As String
        strSQL = " SELECT * FROM orders " & _
        " WHERE OrderID = " & strOrderID & ""
        dtAdapter = New OleDbDataAdapter(strSQL.ToString(), objConn)
        dtAdapter.Fill(dt)
        dtAdapter = Nothing
        objConn.Close()
        objConn = Nothing
        If dt.Rows.Count > 0 Then
            Me.lblOrderID.Text = dt.Rows(0)("OrderID")
            Me.lblOrderDate.Text = dt.Rows(0)("OrderDate")
            Me.lblName.Text = dt.Rows(0)("Name")
            Me.lblAddress.Text = dt.Rows(0)("Address")
            Me.lblTel.Text = dt.Rows(0)("Tel")
            Me.lblEmail.Text = dt.Rows(0)("Email")
        End If
    End Sub
    Protected Sub BindOrderDetails()
        Dim objConn As New OleDbConnection
        Dim dtAdapter As OleDbDataAdapter
        Dim dt As New DataTable
        Dim strConnString As String
        strConnString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=|DataDirectory|\database.mdb"
        objConn = New OleDbConnection(strConnString)
        objConn.Open()
        Dim strSQL As New StringBuilder
        strSQL.Append(" SELECT a.OrderID,a.Qty,b.* FROM orders_detail a ")
        strSQL.Append(" left join product b ")
        strSQL.Append(" on a.ProductID = b.ProductID ")
        strSQL.Append(" WHERE a.OrderID = " & strOrderID & " ")
        dtAdapter = New OleDbDataAdapter(strSQL.ToString(), objConn)
        dtAdapter.Fill(dt)
        dtAdapter = Nothing
        objConn.Close()
        objConn = Nothing
        Me.myGridView.DataSource = dt
        Me.myGridView.DataBind()
    End Sub
    Protected Sub myGridView_RowDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles myGridView.RowDataBound
        If e.Row.RowType = DataControlRowType.DataRow Then
            '*** ProductID ***'
            Dim lblProductID As Label = DirectCast(e.Row.FindControl("lblProductID"), Label)
            If Not IsNothing(lblProductID) Then
                lblProductID.Text = e.Row.DataItem("ProductID")
            End If
            '*** ProductName ***'
            Dim lblProductName As Label = DirectCast(e.Row.FindControl("lblProductName"), Label)
            If Not IsNothing(lblProductName) Then
                lblProductName.Text = e.Row.DataItem("ProductName")
            End If
            '*** Price ***'
            Dim lblPrice As Label = DirectCast(e.Row.FindControl("lblPrice"), Label)
            If Not IsNothing(lblPrice) Then
                lblPrice.Text = e.Row.DataItem("Price")
            End If
            '*** Qty ***'
            Dim lblQty As Label = DirectCast(e.Row.FindControl("lblQty"), Label)
            If Not IsNothing(lblQty) Then
                lblQty.Text = e.Row.DataItem("Qty")
            End If
            '*** Total ***'
            Dim lblTotal As Label = DirectCast(e.Row.FindControl("lblTotal"), Label)
            If Not IsNothing(lblTotal) Then
                strTotal = CDbl(e.Row.DataItem("Qty")) * CDbl(e.Row.DataItem("Price"))
                strSumTotal = CDbl(strSumTotal) + strTotal
                lblTotal.Text = FormatNumber(strTotal, 2)
            End If
        End If
    End Sub
End Class
 
 
 
Code สำหรับภาษา C# 
 
Product.aspx.cs 
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.OleDb;
namespace ShppingCartCS
{
    public partial class Product : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            BindData();
        }
        protected void BindData()
        {
            OleDbConnection objConn = default(OleDbConnection);
            OleDbCommand objCmd = default(OleDbCommand);
            string strConnString = null;
            strConnString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=|DataDirectory|\\database.mdb";
            objConn = new OleDbConnection(strConnString);
            objConn.Open();
            string strSQL = null;
            strSQL = "SELECT * FROM product ";
            OleDbDataReader dtReader = default(OleDbDataReader);
            objCmd = new OleDbCommand(strSQL, objConn);
            dtReader = objCmd.ExecuteReader();
            myGridView.DataSource = dtReader;
            myGridView.DataBind();
            dtReader.Close();
            dtReader = null;
            objConn.Close();
            objConn = null;
        }
        protected void myGridView_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            if (e.CommandName == "Add2Cart")
            {
                string strProductID = e.CommandArgument.ToString();
                DataTable dt = null;
                DataRow dr = null;
                if ((Session["myCart"] == null))
                {
                    dt = new DataTable();
                    dt.Columns.Add("ProductID");
                    dt.Columns.Add("Qty");
                    Session["myCart"] = dt;
                }
                dt = (DataTable)Session["myCart"];
                DataRow[] foundRows = null;
                foundRows = dt.Select("ProductID = '" + strProductID + "'");
                if (foundRows.Length == 0)
                {
                    dr = dt.NewRow();
                    dr["ProductID"] = strProductID;
                    dr["Qty"] = 1;
                    dt.Rows.Add(dr);
                }
                else
                {
                    DataRow[] updateRow = null;
                    updateRow = dt.Select("ProductID = '" + strProductID + "'");
                    updateRow[0]["Qty"] = Convert.ToInt32(updateRow[0]["Qty"]) + 1;
                }
                Session["myCart"] = dt;
                Response.Redirect("ViewCart.aspx");
            }
        }
        protected void myGridView_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                //*** Picture ***//
                Image imgPicture = (Image)e.Row.FindControl("imgPicture");
                if ((imgPicture != null))
                {
                    imgPicture.ImageUrl = "img/" + (string)DataBinder.Eval(e.Row.DataItem, "Picture");
                }
                //*** ProductID ***//
                Label lblProductID = (Label)e.Row.FindControl("lblProductID");
                if ((lblProductID != null))
                {
                    lblProductID.Text = DataBinder.Eval(e.Row.DataItem, "ProductID").ToString();
                }
                //*** ProductName ***//
                Label lblProductName = (Label)e.Row.FindControl("lblProductName");
                if ((lblProductName != null))
                {
                    lblProductName.Text = (string)DataBinder.Eval(e.Row.DataItem, "ProductName");
                }
                //*** Price ***//
                Label lblPrice = (Label)e.Row.FindControl("lblPrice");
                if ((lblPrice != null))
                {
                    lblPrice.Text = DataBinder.Eval(e.Row.DataItem, "Price").ToString();
                }
                //*** AddToCart ***//
                LinkButton lnkAddToCart = (LinkButton)e.Row.FindControl("lnkAddToCart");
                if ((lnkAddToCart != null))
                {
                    lnkAddToCart.Text = "Add";
                    lnkAddToCart.CommandName = "Add2Cart";
                    lnkAddToCart.CommandArgument = DataBinder.Eval(e.Row.DataItem, "ProductID").ToString();
                }
            }
        }
    }
}
 
 
ViewCart.aspx.cs 
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.OleDb;
using System.Text;
namespace ShppingCartCS
{
    public partial class ViewCart : System.Web.UI.Page
    {
        protected double strTotal = 0;
        protected double strSumTotal = 0;
        protected void Page_Load(object sender, EventArgs e)
        {
            BindGird();
            this.lblSumTotal.Text = "Total Amount : " + strSumTotal.ToString("#,###.00");
        }
        protected void BindGird()
        {
            DataTable dt = (DataTable)Session["myCart"];
            this.myGridView.DataSource = dt;
            this.myGridView.DataBind();
        }
        protected void myGridView_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            if (e.CommandName == "Del")
            {
                int RowsID = Convert.ToInt32(e.CommandArgument);
                DataTable dt = null;
                dt = (DataTable)Session["myCart"];
                dt.Rows[RowsID].Delete();
                Session["myCart"] = dt;
                Response.Redirect("ViewCart.aspx");
            }
        }
        protected DataTable getProductDet(string strProductID)
        {
            OleDbConnection objConn = new OleDbConnection();
            OleDbDataAdapter dtAdapter = default(OleDbDataAdapter);
            DataTable dt = new DataTable();
            string strConnString = null;
            strConnString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=|DataDirectory|\\database.mdb";
            objConn = new OleDbConnection(strConnString);
            objConn.Open();
            StringBuilder strSQL = new StringBuilder();
            strSQL.Append(" SELECT * FROM product ");
            strSQL.Append(" WHERE ProductID = " + strProductID + " ");
            dtAdapter = new OleDbDataAdapter(strSQL.ToString(), objConn);
            dtAdapter.Fill(dt);
            dtAdapter = null;
            objConn.Close();
            objConn = null;
            return dt;
        }
        protected void myGridView_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                //*** ProductID ***//
                Label lblProductID = (Label)e.Row.FindControl("lblProductID");
                if ((lblProductID != null))
                {
                    lblProductID.Text = DataBinder.Eval(e.Row.DataItem, "ProductID").ToString();
                }
                DataTable dt = getProductDet(DataBinder.Eval(e.Row.DataItem, "ProductID").ToString());
                //*** ProductName ***//
                Label lblProductName = (Label)e.Row.FindControl("lblProductName");
                if ((lblProductName != null))
                {
                    lblProductName.Text = dt.Rows[0]["ProductName"].ToString();
                }
                //*** Price ***//
                Label lblPrice = (Label)e.Row.FindControl("lblPrice");
                if ((lblPrice != null))
                {
                    lblPrice.Text = dt.Rows[0]["Price"].ToString();
                }
                //*** Qty ***//
                Label lblQty = (Label)e.Row.FindControl("lblQty");
                if ((lblQty != null))
                {
                    lblQty.Text = DataBinder.Eval(e.Row.DataItem, "Qty").ToString();
                }
                //*** Total ***//
                Label lblTotal = (Label)e.Row.FindControl("lblTotal");
                if ((lblTotal != null))
                {
                    strTotal = Convert.ToDouble(DataBinder.Eval(e.Row.DataItem, "Qty")) * Convert.ToDouble(dt.Rows[0]["Price"]);
                    strSumTotal = Convert.ToDouble(strSumTotal) + strTotal;
                    lblTotal.Text = strTotal.ToString("#,###.00");
                }
                //*** Delete ***//
                LinkButton lnkDelete = (LinkButton)e.Row.FindControl("lnkDelete");
                if ((lnkDelete != null))
                {
                    lnkDelete.Text = "Delete";
                    lnkDelete.CommandName = "Del";
                    lnkDelete.CommandArgument = e.Row.RowIndex.ToString();
                    lnkDelete.Attributes.Add("OnClick", "return confirm('Delete this row?');");
                }
            }
        }
        protected void lnkClearCart_Click(object sender, EventArgs e)
        {
                    Session.Abandon();
                    Response.Redirect("ViewCart.aspx");
        }
        protected void lnkCheckOut_Click(object sender, EventArgs e)
        {
            DataTable dt = (DataTable)Session["myCart"];
            if (Session["myCart"] != null)
            {
                if (dt.Rows.Count > 0)
                {
                    this.pnlCheckOut.Visible = true;
                }
            }
        }
        protected void btnSave_Click(object sender, EventArgs e)
        {
            OleDbConnection objConn = new OleDbConnection();
            string strConnString = null;
            string strSQL = null;
            OleDbDataAdapter dtAdapter = default(OleDbDataAdapter);
            DataTable dt1 = new DataTable();
            DataTable dt2 = null;
            string strOrderID = "0";
            int i = 0;
            strConnString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=|DataDirectory|\\database.mdb";
            objConn.ConnectionString = strConnString;
            objConn.Open();
            //*** Insert to orders ***//
            strSQL = "INSERT INTO orders (OrderDate,Name,Address,Tel,Email) " + " VALUES " + " (@sOrderDate,@sName,@sAddress,@sTel,@sEmail)";
            OleDbCommand objCmd = new OleDbCommand(strSQL, objConn);
            objCmd.Parameters.Add("@sOrderDate", OleDbType.Date).Value = DateTime.Now.ToString();
            objCmd.Parameters.Add("@sName", OleDbType.VarChar).Value = this.txtName.Text;
            objCmd.Parameters.Add("@sAddress", OleDbType.VarChar).Value = this.txtAddress.Text;
            objCmd.Parameters.Add("@sTel", OleDbType.VarChar).Value = this.txtTel.Text;
            objCmd.Parameters.Add("@sEmail", OleDbType.VarChar).Value = this.txtEmail.Text;
            objCmd.ExecuteNonQuery();
            //*** Select OrderID ***//
            strSQL = "SELECT Max(OrderID) As sOrderID FROM orders ";
            dtAdapter = new OleDbDataAdapter(strSQL.ToString(), objConn);
            dtAdapter.Fill(dt1);
            if (dt1.Rows.Count > 0)
            {
                strOrderID = dt1.Rows[0]["sOrderID"].ToString();
            }
            //*** Insert to orders_detail ***//
            dt2 = (DataTable)Session["myCart"];
            for (i = 0; i <= dt2.Rows.Count - 1; i++)
            {
                strSQL = "INSERT INTO orders_detail (OrderID,ProductID,Qty) " + " VALUES " + " ('" + strOrderID + "','" + dt2.Rows[i]["ProductID"] + "','" + dt2.Rows[i]["Qty"] + "')";
                var _with1 = objCmd;
                _with1.Connection = objConn;
                _with1.CommandText = strSQL;
                _with1.CommandType = CommandType.Text;
                _with1.ExecuteNonQuery();
            }
            objConn.Close();
            objConn = null;
            Session.Abandon();
            Response.Redirect("ViewOrders.aspx?OrderID=" + strOrderID);
        }
    }
}
 
 
ViewOrders.aspx.cs 
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.OleDb;
using System.Text;
namespace ShppingCartCS
{
    public partial class ViewOrders : System.Web.UI.Page
    {
        protected string strOrderID = HttpContext.Current.Request.QueryString["OrderID"].ToString();
        protected double strTotal = 0;
        protected double strSumTotal = 0;
        protected void Page_Load(object sender, EventArgs e)
        {
            BindCustomer();
            BindOrderDetails();
            this.lblSumTotal.Text = "Total Amount : " + strSumTotal.ToString("#,###.00");
        }
        protected void BindCustomer()
        {
            OleDbConnection objConn = new OleDbConnection();
            OleDbDataAdapter dtAdapter = default(OleDbDataAdapter);
            DataTable dt = new DataTable();
            string strConnString = null;
            strConnString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=|DataDirectory|\\database.mdb";
            objConn = new OleDbConnection(strConnString);
            objConn.Open();
            string strSQL = null;
            strSQL = " SELECT * FROM orders " + " WHERE OrderID = " + strOrderID + "";
            dtAdapter = new OleDbDataAdapter(strSQL.ToString(), objConn);
            dtAdapter.Fill(dt);
            dtAdapter = null;
            objConn.Close();
            objConn = null;
            if (dt.Rows.Count > 0)
            {
                this.lblOrderID.Text = dt.Rows[0]["OrderID"].ToString();
                this.lblOrderDate.Text = dt.Rows[0]["OrderDate"].ToString();
                this.lblName.Text = dt.Rows[0]["Name"].ToString();
                this.lblAddress.Text = dt.Rows[0]["Address"].ToString();
                this.lblTel.Text = dt.Rows[0]["Tel"].ToString();
                this.lblEmail.Text = dt.Rows[0]["Email"].ToString();
            }
        }
        protected void BindOrderDetails()
        {
            OleDbConnection objConn = new OleDbConnection();
            OleDbDataAdapter dtAdapter = default(OleDbDataAdapter);
            DataTable dt = new DataTable();
            string strConnString = null;
            strConnString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=|DataDirectory|\\database.mdb";
            objConn = new OleDbConnection(strConnString);
            objConn.Open();
            StringBuilder strSQL = new StringBuilder();
            strSQL.Append(" SELECT a.OrderID,a.Qty,b.* FROM orders_detail a ");
            strSQL.Append(" left join product b ");
            strSQL.Append(" on a.ProductID = b.ProductID ");
            strSQL.Append(" WHERE a.OrderID = " + strOrderID + " ");
            dtAdapter = new OleDbDataAdapter(strSQL.ToString(), objConn);
            dtAdapter.Fill(dt);
            dtAdapter = null;
            objConn.Close();
            objConn = null;
            this.myGridView.DataSource = dt;
            this.myGridView.DataBind();
        }
        protected void myGridView_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                //*** ProductID ***'
                Label lblProductID = (Label)e.Row.FindControl("lblProductID");
                if ((lblProductID != null))
                {
                    lblProductID.Text = DataBinder.Eval(e.Row.DataItem, "ProductID").ToString();
                }
                //*** ProductName ***'
                Label lblProductName = (Label)e.Row.FindControl("lblProductName");
                if ((lblProductName != null))
                {
                    lblProductName.Text = DataBinder.Eval(e.Row.DataItem, "ProductName").ToString();
                }
                //*** Price ***'
                Label lblPrice = (Label)e.Row.FindControl("lblPrice");
                if ((lblPrice != null))
                {
                    lblPrice.Text = DataBinder.Eval(e.Row.DataItem, "Price").ToString();
                }
                //*** Qty ***'
                Label lblQty = (Label)e.Row.FindControl("lblQty");
                if ((lblQty != null))
                {
                    lblQty.Text = DataBinder.Eval(e.Row.DataItem, "Qty").ToString();
                }
                //*** Total ***'
                Label lblTotal = (Label)e.Row.FindControl("lblTotal");
                if ((lblTotal != null))
                {
                    strTotal = Convert.ToDouble(DataBinder.Eval(e.Row.DataItem, "Qty")) * Convert.ToDouble(DataBinder.Eval(e.Row.DataItem, "Price"));
                    strSumTotal = Convert.ToDouble(strSumTotal) + strTotal;
                    lblTotal.Text = strTotal.ToString("#,###.00");
                }
                //*** Delete ***'
                LinkButton lnkDelete = (LinkButton)e.Row.FindControl("lnkDelete");
                if ((lnkDelete != null))
                {
                    lnkDelete.Text = "Delete";
                    lnkDelete.CommandName = "Del";
                    lnkDelete.CommandArgument = e.Row.RowIndex.ToString();
                    lnkDelete.Attributes.Add("OnClick", "return confirm('Delete this row?');");
                }
            }
        }
    }
}
 
 
Screenshot 
 
  
 
หน้าจอแสดง Product รายการสินค้า มีปุ่มคลิกสั่งซื้อ 
 
 
  
 
แสดงรายการสินค้าในตะกร้า ที่ได้เลือกสั่งซื้อ สามารถกลับไปเลือกสินค้าต่อ หรือจะลบรายการที่เลือก หรือจะ Checkout เพื่อไปขั้นตอนถัดไป 
 
 
  
 
หน้าจอสำหรับ Checkout มีให้กรอกข้อมูลชื่อและข้อมูลอื่น ๆ ของผู้สั่งซื้อ 
 
 
  
 
เมื่อการสั่งซื้อเรียบร้อยแล้ว ก็จะแสดงรายรายละเอียดที่ได้สั่งซื้อ  
 
เพิ่มเติม 
Code และตัวอย่างนี้เป็นเพียงตัวอย่างง่าย ๆ แต่สามารถดัดแปลงการใช้งาน เช่นการใช้ระบบสมาชิกเข้ามาเกี่ยวข้อง หรือระบบอื่น ๆ ขึ้นอยู่กับความต้องการ 
 
 
Download Code !! 
 
 
 
 
บทความอื่น ๆ ที่เกี่ยวข้อง 
Go to : PHP สร้างระบบตะกร้า Shopping Cart ด้วย Session และ Array 
Go to : ASP.NET - Session (DataSet and DataTable) 
Go to : ASP.NET Session Variables  
  			     
			                 
			  
			               				
               
			
			
	  			  
                           
                             |   | 
                               | 
                              
                                  | 
                            
                           
                             | 
 | 
                               | 
                            
               
               
  | 
           
         
		
	
	
        
          
            
                
                   | 
                 
                
                  |   | 
                  Score Rating :  | 
                  
                                         | 
                 
                
                  |   | 
                  Create Date :  | 
                  2012-03-16 15:37:15 | 
                 
                
                  |   | 
                  View :  | 
                  
                    47,303                   | 
                 
                
                  |   | 
                  Download :  | 
                  
                     No files
					
				   | 
                 
                
                  |   | 
                    | 
                    | 
                 
              | 
           
         
	
        
        
		 | 
     
   
 
		  
          | 
		
          
		   
		  
              
      
     |