ASP.NET購物車實現過程詳解_實用技巧

來源:互聯網
上載者:User

1、 將test資料庫附加到資料庫管理系統中;資料庫中的book_info包含下列資料:

2、 建立一個網站,將images檔案夾複製到網站中;
3、 在Default.aspx中,通過DataList控制項展示資料庫中的所有資料,以行為主序,每行3列,單擊購買按鈕時,將商品的ID和數量儲存到HashTable中,並將HashTable放置到Session中。

protected void DataList1_ItemCommand(object source, DataListCommandEventArgs e)   {     string id = e.CommandArgument.ToString();     Hashtable ht;     if (Session["shopcar"] == null)     {       ht = new Hashtable();       ht.Add(id, 1);       Session["shopcar"] = ht;     }     else     {       ht = (Hashtable)Session["shopcar"];       if (ht.Contains(id))       {         int count = int.Parse(ht[id].ToString());         ht[id] = count + 1;         Session["shopcar"] = ht;         Response.Write(count + 1);       }       else       {         ht.Add(id, 1);         Session["shopcar"] = ht;       }     }   } 

4、 在Default.aspx中添加一個超連結,連結到shopcart.aspx,在shopcart.aspx中顯示使用者購買的商品資訊。
提示:

A、在shopcart中先定義下列變數:

Hashtable ht;  DataTable dt;  string connstring=@"DataSource=.\SQLEXPRESS;Initial Catalog=test;Integrated Security=True";  SqlConnection conn;  SqlCommand cmd; SqlDataReader sdr;

B、頁面中添加一個GridView。
C、在page_load中,將dt執行個體化,建立各列。

protected void Page_Load(object sender, EventArgs e)  {    dt = new DataTable();    DataColumn col = new DataColumn();    col.ColumnName= "id";    col.DataType =System.Type.GetType("System.String");    dt.Columns.Add(col);    col = new DataColumn();    col.ColumnName= "name";    col.DataType =System.Type.GetType("System.String");    dt.Columns.Add(col);    col = new DataColumn();    col.ColumnName= "Num";    col.DataType =System.Type.GetType("System.Int32");    dt.Columns.Add(col);    col = new DataColumn();    col.ColumnName= "price";    col.DataType =System.Type.GetType("System.Single");    dt.Columns.Add(col);    col = new DataColumn();    col.ColumnName= "Total";    col.DataType =System.Type.GetType("System.Single");    dt.Columns.Add(col);    if (!IsPostBack)    {      Bind();    }  }    public void Bind()  {         if (Session["shopcar"] == null)    {      Response.Write("<script>if(confirm('你沒有登入')window.location='Default15.aspx';else window.close();</script>");    }    else    {      ht = (Hashtable)Session["shopcar"];      foreach (object item in ht.Keys)      {        string id = item.ToString();        int num = int.Parse(ht[item].ToString());        string sql = "selectbook_name,price from book_info where book_id='" + id + "'";        conn = new SqlConnection(connstring);        cmd = new SqlCommand(sql, conn);        conn.Open();        sdr =cmd.ExecuteReader();        if (sdr.HasRows)        {          sdr.Read();          DataRow row = dt.NewRow();          row["id"] = id;          row["Num"] = num;          row["name"] = sdr.GetString(0);          row["price"] =float.Parse(sdr[1].ToString());          row["total"] =num*(float.Parse(sdr[1].ToString()));          dt.Rows.Add(row);        }        sdr.Close();        conn.Close();                     }      GridView1.DataSource = dt.DefaultView;      GridView1.DataBind();    }}

D、這時可以看到使用者購買的商品,但不能修改數量,也不能刪除。
E、添加修改數量,刪除商品功能,在aspx頁面中定義GridView中的各列:

 <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False">     <Columns>       <asp:BoundField DataField="id" HeaderText="ID" />       <asp:BoundField DataField="name" HeaderText="名稱" />       <asp:BoundField DataField="price" HeaderText="價格" />       <asp:TemplateField>              <ItemTemplate>         <asp:TextBox runat="server" ID="textbox1" Text='<%# Eval("Num") %>'            ontextchanged="textbox1_TextChanged" AutoPostBack="True" ></asp:TextBox>        </ItemTemplate>             </asp:TemplateField>      <asp:BoundField DataField="total" HeaderText="總計" />      <asp:TemplateField>       <ItemTemplate>        <asp:Button runat="server" ID="button1" CommandArgument='<%# Eval("id") %>'           Text="刪除" onclick="button1_Click" />              </ItemTemplate>            </asp:TemplateField>     </Columns>         </asp:GridView>

F、為GridView中的文字框添加TextChanged事件:

protected void textbox1_TextChanged(object sender, EventArgs e)  {        Hashtable ht =(Hashtable)Session["shopcar"];    if (ht == null) return;    for (int i = 0; i < GridView1.Rows.Count;i++)    {      string id =GridView1.Rows[i].Cells[0].Text.ToString();      Response.Write(id);      string num = ((TextBox)GridView1.Rows[i].FindControl("textbox1")).Text;      Response.Write("  "+num+"<br />");      ht[id] = num;    }    Session["shopcar"] = ht;    Bind();     }

G、為按鈕添加單擊事件:

protected void button1_Click(object sender, EventArgs e)  {    string id = ((Button)sender).CommandArgument;    Hashtable ht = (Hashtable)Session["shopcar"];    if (ht == null) return;    ht.Remove(id);    Bind();}

購物車代碼:showcart.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.Collections; using System.Data; using System.Data.SqlClient;  public partial class shopcart : System.Web.UI.Page {   Hashtable ht;   DataTable dt;   string connstr = "Data Source=.\\SQLEXPRESS;AttachDbFilename=F:\\test.mdf;Integrated Security=True;Connect Timeout=30;User Instance=True";   SqlConnection conn;   SqlCommand cmd;   SqlDataReader sdr;   protected void Page_Load(object sender, EventArgs e)   {     dt = new DataTable();     DataColumn col = new DataColumn();     col.ColumnName = "id";     col.DataType = System.Type.GetType("System.String");     dt.Columns.Add(col);     col = new DataColumn();     col.ColumnName = "name";     col.DataType = System.Type.GetType("System.String");     dt.Columns.Add(col);     col = new DataColumn();     col.ColumnName = "Num";     col.DataType = System.Type.GetType("System.Int32");     dt.Columns.Add(col);     col = new DataColumn();     col.ColumnName = "price";     col.DataType = System.Type.GetType("System.Single");     dt.Columns.Add(col);     col = new DataColumn();     col.ColumnName = "Total";     col.DataType = System.Type.GetType("System.Single");     dt.Columns.Add(col);      if (!IsPostBack)     {       Bind();     }    }    public void Bind()   {     if (Session["shopcar"] == null)     {       Response.Write("<script>if(confirm('你沒有登入')window.location='Default.aspx';else window.close();</script>");     }     else     {       ht = (Hashtable)Session["shopcar"];       foreach (object item in ht.Keys)       {         string id = item.ToString();          int num = int.Parse((ht[item].ToString()));         string sql = "select book_name,price from book_info where book_id='" + id + "'";         conn = new SqlConnection(connstr);          cmd = new SqlCommand(sql, conn);         conn.Open();          sdr = cmd.ExecuteReader();         if (sdr.HasRows)         {           sdr.Read();           DataRow row = dt.NewRow();           row["id"] = id;           row["Num"] = num;           row["name"] = sdr.GetString(0);           row["price"] = float.Parse(sdr[1].ToString());           row["total"] = num * (float.Parse(sdr[1].ToString()));           dt.Rows.Add(row);          }         sdr.Close();         conn.Close();       }     }     GridView1.DataSource = dt.DefaultView;     GridView1.DataBind();    }   protected void textbox1_TextChanged(object sender, EventArgs e)   {     Hashtable ht = (Hashtable)Session["shopcar"];     if (ht == null) return;     for (int i = 0; i < GridView1.Rows.Count; i++)     {       string id = GridView1.Rows[i].Cells[0].Text.ToString();       Response.Write(id);       string num = ((TextBox)GridView1.Rows[i].FindControl("textbox1")).Text;       Response.Write("  " + num + "<br />");       ht[id] = num;     }     Session["shopcar"] = ht;     Bind();    }   protected void button1_Click(object sender, EventArgs e)   {     string id = ((Button)sender).CommandArgument;     Hashtable ht = (Hashtable)Session["shopcar"];     if (ht == null) return;     ht.Remove(id);     Bind();    } } 

製作一個簡單的購物車就是這麼簡單,大家可以按照我的思路進行創作,在此基礎上在添加一些功能。

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.