1private void DataGrid1_ItemCommand(object source, System.Web.UI.WebControls.DataGridCommandEventArgs e)//Assume that the previous purchase command is a LinkButton with a command name buy
2 {//Key, create and add to shopping cart
3 string pid=this.DataGrid1.DataKeys[e.Item.ItemIndex].ToString();//Get the pet number
4 if(e.CommandName=="buy")//If the command name is buy, it means buying
5 {
6 if(Session["bus"]==null)//First check whether the shopping cart exists. If it does not exist, create it.
7 {
8 System.Collections.Hashtable ht=new Hashtable();//First create a hash table
9 ht.Add(pid,1);//There are two columns in the hash table, one key and one value. We put the pet number in the front and the purchase quantity in the back. The default setting is 1
10 Session["bus"]=ht;//Assign the hash table to the Session object
11 }
12 else//if exists
13 {
14 Hashtable ht=(Hashtable)Session["bus"];//Use forced type conversion, and then assign Session["bus"] to the hash table object ht
15 if(ht[pid]==null)//If the corresponding ID is not in the hash table,
16 {
17 ht[pid]=1;//Then set it to 1 directly
18}
19 else//If there is already a corresponding ID
20 {
21 ht[pid]=(int)ht[pid]+1;//Then take out the original and add 1
twenty two }
23 Session["bus"]=ht;//Finally update the Session object
twenty four }
25}
26
27}
The reading method is simpler, as follows:
this.DataList1.DataSource=(Hashtable)Session["bus"];//Use the hash table directly as the data source,
this.DataList1.DataBind();//Bind the update quantity
1private void LinkButton1_Click(object sender, System.EventArgs e)
2 {
3
4 foreach(DataListItem dl in this.DataList1.Items)//Traverse the collection
5 {
6 TextBox tb=(TextBox)dl.FindControl("TextBox1");//Find the text box
7 int newpid=Convert.ToInt32(tb.Text.ToString());//Find the value in the text box
8
9 Label label1=(Label)dl.FindControl("key");//Find the control that loads the key field of the hash table
10 string pid=label1.Text.ToString();//Get his value
11
12 Hashtable ht=(Hashtable)Session["bus"];//Assign the session["bus"] object to the hash table ht
13 int oldpid=(int)ht[pid];//Get the original quantity
14
15 if(newpid!=oldpid)//If the value in the text box is not equal to the original number, replace it with the new value in the hash table
16 {
17 ht[pid]=newpid;
18}
19 Session["bus"]=ht;//Finally update the Session object
20}
twenty one }