ASP. NET shopping cart implementation process details, asp.net shopping cart details

Source: Internet
Author: User

ASP. NET shopping cart implementation process details, asp.net shopping cart details

1. Attach the test database to the database management system. The book_info in the database contains the following data:

2. Create a new website and copy the images folder to the website;
3. In Default. in aspx, The DataList control is used to display all data in the database. In the active order of behavior, three columns are displayed in each row. When you click the Buy button, the IDs and quantities of the items are saved to HashTable, and place HashTable in the 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. Add a hyperlink to the Default. aspx file to link to shopcart. aspx. The shopcart. aspx file displays the product information you have purchased.
Tip:

A. Define the following variables in shopcart:

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

B. Add a GridView to the page.
C. In page_load, instantiate dt and create columns.

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 ('You are not logged on') 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. You can see the purchased items, but you cannot modify the quantity or delete them.
E. Add or modify the quantity and delete items. On the aspx page, define the columns in the GridView:

<Asp: GridView ID = "GridView1" runat = "server" AutoGenerateColumns = "False"> <Columns> <asp: boundField DataField = "id" HeaderText = "ID"/> <asp: BoundField DataField = "name" HeaderText = "name"/> <asp: boundField DataField = "price" HeaderText = "price"/> <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 = "total"/> <asp: TemplateField> <ItemTemplate> <asp: button runat = "server" ID = "button1" CommandArgument = '<% # Eval ("id ") %> 'text = "delete" onclick = "button?click"/> </ItemTemplate> </asp: TemplateField> </Columns> </asp: GridView>

F. Add the TextChanged event to the text box in the GridView:

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. Add a click event for the button:

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();}

Shopping Cart code: 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 ('You are not logged on') 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 button#click (object sender, EventArgs e) {string id = (Button) sender ). commandArgument; Hashtable ht = (Hashtable) Session ["shopcar"]; if (ht = null) return; ht. remove (id); Bind ();}}

Creating a simple shopping cart is that simple. You can create a shopping cart based on your ideas and add some functions.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.