|
|
| 利用Session和HashTable制作购物车 |
| 作者:不详 来源:不详 发布时间:2006-8-14 8:37:56 发布人:chinazhan |
减小字体
增大字体
1 private void DataGrid1_ItemCommand(object source, System.Web.UI.WebControls.DataGridCommandEventArgs e)//假设前面购买命令是一个命令名为buy的LinkButton 2 {//关键,建立和加如购物车 3 string pid=this.DataGrid1.DataKeys[e.Item.ItemIndex].ToString();//取出宠物编号 4 if(e.CommandName=="buy")//如果命令名是 buy,说明是购买 5 { 6 if(Session["bus"]==null)//先就得检查购物车是否存在,如果不存在,就建立呗 7 { 8 System.Collections.Hashtable ht=new Hashtable();//先建立一个哈希表 9 ht.Add(pid,1);//哈希表中的两个列,一个key,一个value ,我们就前面放宠物编号,后面放购买数量好了,预设置为1 10 Session["bus"]=ht;//将哈希表赋值给Session对象 11 } 12 else//如果存在的话 13 { 14 Hashtable ht=(Hashtable)Session["bus"];//使用强制类型转换,再将Session["bus"]赋值给哈希表对象 ht 15 if(ht[pid]==null)//如果哈希表中对应的ID没有, 16 { 17 ht[pid]=1;//那就直接给他设为 1 18 } 19 else//如果已经有对应的ID 20 { 21 ht[pid]=(int)ht[pid]+1;//那么就把原来的取出来再加上 1 22 } 23 Session["bus"]=ht;//最后再更新Session 对象 24 } 25 } 26 27 } 而读取的方法更简单了,如下: this.DataList1.DataSource=(Hashtable)Session["bus"];//直接利用哈希表作为数据源, this.DataList1.DataBind();//绑定一下 www.knowsky.com 更新数量 1private void LinkButton1_Click(object sender, System.EventArgs e) 2 { 3 4 foreach(DataListItem dl in this.DataList1.Items)//遍历集合 5 { 6 TextBox tb=(TextBox)dl.FindControl("TextBox1");//找到文本框 7 int newpid=Convert.ToInt32(tb.Text.ToString());//查出文本框里面的值 8 9 Label label1=(Label)dl.FindControl("key");//找到装载哈希表key字段的那个控件 10 string pid=label1.Text.ToString();//把他的值拿出来 11 12 Hashtable ht=(Hashtable)Session["bus"];//把session["bus"]对象赋值给哈希表 ht 13 int oldpid=(int)ht[pid];//求得原来的数量 14 15 if(newpid!=oldpid)//如果文本框里的值不等于原来的数量,就用新的更换到哈希表中的值 16 { 17 ht[pid]=newpid; 18 } 19 Session["bus"]=ht;//最后再更新Session 对象 20 } 21 } 出处:.net入门ing…… BLOG 做人要厚道,请注明转自chinazhan中国站长(www.ChinaZhan.com)。
|
| |
|
[]
[返回上一页]
[打 印]
[收 藏] |
|
| ∷相关文章评论∷ (评论内容只代表网友观点,与本站立场无关!) [更多评论...] |
|
|