c#利用Session对象实现购物车的方法示例
程序员文章站
2022-06-30 09:56:59
本文实现了c# session对象实现购物车的方法,分享给大家,也给自己留个笔记://shopcart.aspx.csusing system;using system.data;using syst...
本文实现了c# session对象实现购物车的方法,分享给大家,也给自己留个笔记:
//shopcart.aspx.cs using system; using system.data; using system.configuration; using system.collections; using system.web; using system.web.security; using system.web.ui; using system.web.ui.webcontrols; using system.web.ui.webcontrols.webparts; using system.web.ui.htmlcontrols; using system.data.sqlclient; using system.text.regularexpressions; public partial class shopcart : system.web.ui.page { commonclass ccobj = new commonclass(); dbclass dbobj = new dbclass(); string strsql; datatable dttable; hashtable hashcar; protected void page_load(object sender, eventargs e) { if (!ispostback) { if (session["shopcart"] == null) { //如果没有购物,则给出相应信息,并隐藏按钮 this.labmessage.text = "您还没有购物!"; this.labmessage.visible = true; //显示提示信息 this.lnkbtncheck.visible = false; //隐藏“前往服务台”按钮 this.lnkbtnclear.visible = false; //隐藏“清空购物车”按钮 this.lnkbtncontinue.visible = false; //隐藏“继续购物”按钮 } else { hashcar = (hashtable)session["shopcart"]; //获取其购物车 if (hashcar.count == 0) { //如果没有购物,则给出相应信息,并隐藏按钮 this.labmessage.text = "您购物车中没有商品!"; this.labmessage.visible = true; //显示提示信息 this.lnkbtncheck.visible = false; //隐藏“前往服务台”按钮 this.lnkbtnclear.visible = false; //隐藏“清空购物车”按钮 this.lnkbtncontinue.visible = false; //隐藏“继续购物”按钮 } else { //设置购物车内容的数据源 dttable = new datatable(); datacolumn column1 = new datacolumn("no"); //序号列 datacolumn column2 = new datacolumn("bookid"); //书籍id代号 datacolumn column3 = new datacolumn("bookname"); //书籍名称 datacolumn column4 = new datacolumn("num"); //数量 datacolumn column5 = new datacolumn("price"); //单价 datacolumn column6 = new datacolumn("totalprice");//总价 dttable.columns.add(column1); //添加新列 dttable.columns.add(column2); dttable.columns.add(column3); dttable.columns.add(column4); dttable.columns.add(column5); dttable.columns.add(column6); datarow row; //对数据表中每一行进行遍历,给每一行的新列赋值 //foreach (object key in hashcar.keys) //{ // row = dttable.newrow(); // row["bookid"] = key.tostring(); // row["num"] = hashcar[key].tostring(); // dttable.rows.add(row); //} foreach (dictionaryentry hash in hashcar) { row = dttable.newrow(); row["bookid"] = hash.key.tostring(); row["num"] = hash.value.tostring(); dttable.rows.add(row); } //计算价格 datatable dstable; int i = 1; float price;//商品单价 int count; //商品数量 float totalprice = 0; //商品总价格 foreach (datarow drrow in dttable.rows) { strsql = "select bookname,hotprice from tb_bookinfo where bookid=" + convert.toint32(drrow["bookid"].tostring()); dstable = dbobj.getdatasetstr(strsql, "tbgi"); drrow["no"] = i;//序号 drrow["bookname"] = dstable.rows[0][0].tostring();//书籍名称 drrow["price"] = (dstable.rows[0][1].tostring());//单价 price = float.parse(dstable.rows[0][1].tostring());//单价 count = int32.parse(drrow["num"].tostring()); drrow["totalprice"] = price * count; //总价 totalprice += price * count; //计算合价 i++; } this.labtotalprice.text = "总价:" + totalprice.tostring(); //显示所有商品的价格 this.gvshopcart.datasource = dttable.defaultview; //绑定gridview控件 this.gvshopcart.datakeynames = new string[] { "bookid" }; this.gvshopcart.databind(); } } } } public void bind() { if (session["shopcart"] == null) { //如果没有购物,则给出相应信息,并隐藏按钮 this.labmessage.text = "您还没有购物!"; this.labmessage.visible = true; //显示提示信息 this.lnkbtncheck.visible = false; //隐藏“前往服务台”按钮 this.lnkbtnclear.visible = false; //隐藏“清空购物车”按钮 this.lnkbtncontinue.visible = false; //隐藏“继续购物”按钮 } else { hashcar = (hashtable)session["shopcart"]; //获取其购物车 if (hashcar.count == 0) { //如果没有购物,则给出相应信息,并隐藏按钮 this.labmessage.text = "您购物车中没有商品!"; this.labmessage.visible = true; //显示提示信息 this.lnkbtncheck.visible = false; //隐藏“前往服务台”按钮 this.lnkbtnclear.visible = false; //隐藏“清空购物车”按钮 this.lnkbtncontinue.visible = false; //隐藏“继续购物”按钮 } else { //设置购物车内容的数据源 dttable = new datatable(); datacolumn column1 = new datacolumn("no"); //序号列 datacolumn column2 = new datacolumn("bookid"); //书籍id代号 datacolumn column3 = new datacolumn("bookname"); //书籍名称 datacolumn column4 = new datacolumn("num"); //数量 datacolumn column5 = new datacolumn("price"); //单价 datacolumn column6 = new datacolumn("totalprice");//总价 dttable.columns.add(column1); //添加新列 dttable.columns.add(column2); dttable.columns.add(column3); dttable.columns.add(column4); dttable.columns.add(column5); dttable.columns.add(column6); datarow row; //对数据表中每一行进行遍历,给每一行的新列赋值 foreach (object key in hashcar.keys) { row = dttable.newrow(); row["bookid"] = key.tostring(); row["num"] = hashcar[key].tostring(); dttable.rows.add(row); } //计算价格 datatable dstable; int i = 1; float price;//商品单价 int count; //商品数量 float totalprice = 0; //商品总价格 foreach (datarow drrow in dttable.rows) { strsql = "select bookname,hotprice from tb_bookinfo where bookid=" + convert.toint32(drrow["bookid"].tostring()); dstable = dbobj.getdatasetstr(strsql, "tbgi"); drrow["no"] = i;//序号 drrow["bookname"] = dstable.rows[0][0].tostring();//书籍名称 drrow["price"] = (dstable.rows[0][1].tostring());//单价 price = float.parse(dstable.rows[0][1].tostring());//单价 count = int32.parse(drrow["num"].tostring()); drrow["totalprice"] = price * count; //总价 totalprice += price * count; //计算合价 i++; } this.labtotalprice.text = "总价:" + totalprice.tostring(); //显示所有商品的价格 this.gvshopcart.datasource = dttable.defaultview; //绑定gridview控件 this.gvshopcart.datakeynames=new string[] {"bookid"}; this.gvshopcart.databind(); } } } protected void lnkbtnupdate_click(object sender, eventargs e) { hashcar = (hashtable)session["shopcart"]; //获取其购物车 //使用foreach语句,遍历更新购物车中的商品数量 foreach (gridviewrow gvr in this.gvshopcart.rows) { textbox otb = (textbox)gvr.findcontrol("txtnum"); //找到用来输入数量的textbox控件 int count = int32.parse(otb.text);//获得用户输入的数量值 string bookid = gvr.cells[1].text;//得到该商品的id代 hashcar[bookid] = count;//更新hashtable表 } session["shopcart"] = hashcar;//更新购物车 response.redirect("shopcart.aspx"); } protected void lnkbtndelete_command(object sender, commandeventargs e) { hashcar = (hashtable)session["shopcart"];//获取其购物车 //从hashtable表中,将指定的商品从购物车中移除,其中,删除按钮(lnkbtndelete)的commandargument参数值为商品id代号 hashcar.remove(e.commandargument); session["shopcart"] = hashcar; //更新购物车 response.redirect("shopcart.aspx"); } protected void lnkbtnclear_click(object sender, eventargs e) { session["shopcart"] =null; response.redirect("shopcart.aspx"); } protected void lnkbtncontinue_click(object sender, eventargs e) { response.redirect("default.aspx"); } protected void lnkbtncheck_click(object sender, eventargs e) { response.redirect("checkout.aspx"); } protected void gvshopcart_pageindexchanging(object sender, gridviewpageeventargs e) { gvshopcart.pageindex = e.newpageindex; bind(); } protected void txtnum_textchanged(object sender, eventargs e) { hashcar = (hashtable)session["shopcart"]; //获取其购物车 foreach (gridviewrow gvr in this.gvshopcart.rows) { textbox otb = (textbox)gvr.findcontrol("txtnum"); //找到用来输入数量的textbox控件 int count = int32.parse(otb.text);//获得用户输入的数量值 string bookid = gvr.cells[1].text;//得到该商品的id代 hashcar[bookid] = count;//更新hashtable表 } session["shopcart"] = hashcar;//更新购物车 bind(); }
//shopcart.aspx <table cellspacing="0" cellpadding="0" width="95%" align="center" border="0" style="font-size: 9pt"> <tr> <td align="center"> <asp:label id="labmessage" runat="server" visible="false"></asp:label></td> </tr> <tr> <td align="left" height =30px> <asp:label id="labtotalprice" runat="server" text="0.00 " ></asp:label>¥</td> </tr> <tr style =" font :9pt; font-family :宋体;" valign =top > <td align="left" style="height: 135px"> <asp:gridview id="gvshopcart" datakeynames ="bookid" runat="server" autogeneratecolumns="false" allowpaging="true" onpageindexchanging="gvshopcart_pageindexchanging" > <columns> <asp:boundfield datafield="no" headertext="序号" readonly="true"> <itemstyle horizontalalign="center" /> <headerstyle horizontalalign="center" /> </asp:boundfield> <asp:boundfield datafield="bookid" headertext="书籍id" readonly="true"> <itemstyle horizontalalign="center" /> <headerstyle horizontalalign="center" /> </asp:boundfield> <asp:boundfield datafield="bookname" headertext="书籍名称" readonly="true"> <itemstyle horizontalalign="center" /> <headerstyle horizontalalign="center" /> </asp:boundfield> <asp:templatefield headertext="数量"> <itemtemplate > <asp:textbox id="txtnum" runat="server" text =<%#eval("num") %> width =60px ontextchanged="txtnum_textchanged"></asp:textbox> <asp:regularexpressionvalidator id="regularexpressionvalidator1" runat="server" controltovalidate="txtnum" errormessage="×" validationexpression="^\+?[1-9][0-9]*$"></asp:regularexpressionvalidator> </itemtemplate> </asp:templatefield> <asp:templatefield headertext =单价> <headerstyle horizontalalign=center /> <itemstyle horizontalalign =center /> <itemtemplate > <%#eval("price")%>¥ </itemtemplate> </asp:templatefield> <asp:templatefield headertext =总价> <headerstyle horizontalalign=center /> <itemstyle horizontalalign =center /> <itemtemplate > <%#eval("totalprice")%>¥ </itemtemplate> </asp:templatefield> <asp:templatefield> <headerstyle horizontalalign=center /> <itemstyle horizontalalign =center /> <itemtemplate > <asp:linkbutton id="lnkbtndelete" runat="server" commandargument ='<%#eval("bookid") %>' oncommand ="lnkbtndelete_command">删除</asp:linkbutton> </itemtemplate> </asp:templatefield> </columns> </asp:gridview> </td> </tr> <tr align =left valign =top > <td align="center" > <asp:linkbutton id="lnkbtnupdate" runat="server" onclick="lnkbtnupdate_click">更新购物车</asp:linkbutton> <asp:linkbutton id="lnkbtnclear" runat="server" onclick="lnkbtnclear_click" >清空购物车</asp:linkbutton> <asp:linkbutton id="lnkbtncontinue" runat="server" onclick="lnkbtncontinue_click" >继续购物</asp:linkbutton> <asp:linkbutton id="lnkbtncheck" runat="server" onclick="lnkbtncheck_click" >前往服务台</asp:linkbutton> </td> </tr> <tr> <td align="left" > <br /> <li>如果要修改商品数量,请单击“更新购物车”按钮 </li> <li>如果要取消某个商品,请单击“删除” <br /> </li> </td> </tr> </table>
default.aspx.cs //添加物品到购物车代码 protected void dldiscount_itemcommand(object source, datalistcommandeventargs e) { if (e.commandname == "detailsee") { addressback(e); } else if (e.commandname == "buy") { addshopcart(e); } } protected void dlhot_itemcommand(object source, datalistcommandeventargs e) { if (e.commandname == "detailsee") { addressback(e); } else if (e.commandname == "buy") { addshopcart(e); } } /// <summary> /// 向购物车中添加新商品 /// </summary> /// <param name="e"> /// 获取或设置可选参数, /// 该参数与关联的 commandname /// 一起被传递到 command 事件。 /// </param> public void addshopcart(datalistcommandeventargs e) { hashtable hashcar; if (session["shopcart"] == null) { //如果用户没有分配购物车 hashcar = new hashtable(); //新生成一个 hashcar.add(e.commandargument, 1); //添加一个商品 session["shopcart"] = hashcar; //分配给用户 } else { //用户已经有购物车 hashcar = (hashtable)session["shopcart"];//得到购物车的hash表 if (hashcar.contains(e.commandargument))//购物车中已有此商品,商品数量加1 { int count = convert.toint32(hashcar[e.commandargument].tostring());//得到该商品的数量 hashcar[e.commandargument] = (count + 1);//商品数量加1 } else hashcar.add(e.commandargument, 1);//如果没有此商品,则新添加一个项 } } this.clientscript.registerstartupscript(this.gettype(),"",<script>alert("商品添加成功!")</script>);
hashtable实现购物车,先前我们的购物车使用的是数据库方式实现,每次购物都要进行数据库操作,很影响效率。现在我们采用hashtable和session来实现购物车,这样便节省了数据库的操作,大大的提高效率
private void datagrid1_itemcommand(object source, system.web.ui.webcontrols.datagridcommandeventargs e)//假设前面购买命令是一个命令名为buy的linkbutton {//关键,建立和加如购物车 string pid=this.datagrid1.datakeys[e.item.itemindex].tostring();//取出编号 if(e.commandname=="buy")//如果命令名是 buy,说明是购买 { if(session["bus"]==null)//先就得检查购物车是否存在,如果不存在,就建立 { system.collections.hashtable ht=new hashtable();//先建立一个哈希表 ht.add(pid,1);//哈希表中的两个列,一个key,一个value ,key放编号,value放购买数量好了,预设置为1 session["bus"]=ht;//将哈希表赋值给session对象 } else//如果存在的话 { hashtable ht=(hashtable)session["bus"];//使用强制类型转换,再将session["bus"]赋值给哈希表对象 ht if(ht[pid]==null)//如果哈希表中对应的id没有, { ht[pid]=1;//那就直接给他设为 1 } else//如果已经有对应的id { ht[pid]=(int)ht[pid]+1;//那么就把原来的取出来再加上 1 } session["bus"]=ht;//最后再更新session 对象 } } }
而读取的方法如下:
this.datalist1.datasource=(hashtable)session["bus"]; this.datalist1.databind(); 1private void linkbutton1_click(object sender, system.eventargs e) { foreach(datalistitem dl in this.datalist1.items)//遍历集合 { textbox tb=(textbox)dl.findcontrol("textbox1");//找到文本框 int newpid=convert.toint32(tb.text.tostring());//查出文本框里面的值 label label1=(label)dl.findcontrol("key");//找到装载哈希表key字段的那个控件 string pid=label1.text.tostring();//把他的值拿出来 hashtable ht=(hashtable)session["bus"];//把session["bus"]对象赋值给哈希表 ht int oldpid=(int)ht[pid];//求得原来的数量 if(newpid!=oldpid)//如果文本框里的值不等于原来的数量,就用新的更换到哈希表中的值 { ht[pid]=newpid; } session["bus"]=ht;//最后再更新session 对象 } }
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。
上一篇: C#中多态性的实现
下一篇: PHP回调函数简单用法示例