ASP.NET.Notes.on.Shopping.Cart.Codes by nuhman10

VIEWS: 24 PAGES: 9

									                             Shopping Cart Example
                                       Default.aspx
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs"
Inherits="_Default" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server"><title>Untitled Page</title>
</head><body>
     <form id="form1" runat="server">
     <div>
          <asp:GridView ID="GridView1" runat="server">
                <Columns>
                      <asp:TemplateField HeaderText="adCart">
                           <ItemTemplate>
                                <asp:CheckBox ID="adcCheck" runat="server" />
                           </ItemTemplate>
                      </asp:TemplateField>
                </Columns>
          </asp:GridView>
          <asp:Button ID="Button1" runat="server" onclick="Button1_Click" Text="Add
To Cart" />
     </div>
     </form>
</body></html>
                                      Default.aspx.cs
public partial class _Default:System.Web.UI.Page {
     protected void Page_Load(object sender,EventArgs e) {
          SqlConnection conn; SqlDataAdapter sda; DataSet ds;
          if(!IsPostBack) {
                ds=new DataSet();
                conn=new SqlConnection(@"Data
Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|EasyBuy.mdf;Integrated
Security=True;User Instance=True");
                conn.Open();
                sda=new SqlDataAdapter("Select * from products where
Brand='hp'",conn);
                sda.Fill(ds);
                this.GridView1.DataSource=ds.Tables[0];
                this.GridView1.DataBind();
          }
     }
     protected void Button1_Click(object sender,EventArgs e) {
          Boolean flag=false;


                                    Page 1 of 9
          foreach(GridViewRow gvr in GridView1.Rows) {
               CheckBox ch=(CheckBox)gvr.FindControl("adcCheck");
               if(ch.Checked) {
                     flag=false;
                     CartItem c=new CartItem();
c.Productid=Convert.ToInt32(gvr.Cells[1].Text);
                     c.Brand=gvr.Cells[2].Text;
                     c.Price=Convert.ToDouble(gvr.Cells[11].Text);
                     c.Quantity=1;
                     if(Session["cart"]==null) {
                           List<CartItem> list=new List<CartItem>();
                           list.Add(c);
                           Session["cart"]=list;
                     } else {
            List<CartItem>list=(List<CartItem>)Session["cart"];
                           foreach(CartItem ci in list) {
                                  if(ci.Productid==c.Productid) {
                                        ci.Quantity++;
                                        flag=true;
                                        break;
                                  }
                           }if(!flag) list.Add(c);
                     }
               }
          }
         Server.Transfer("Default2.aspx");
     }
}
                                           Default2.aspx
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default2.aspx.cs"
Inherits="Default2" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server"><title>Untitled Page</title>
</head><body>
     <form id="form1" runat="server">
     <div>
          <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"
               AutoGenerateDeleteButton="True" AutoGenerateEditButton="True"
               onrowcancelingedit="GridView1_RowCancelingEdit"
               onrowdeleting="GridView1_RowDeleting"
onrowediting="GridView1_RowEditing"
               onrowupdating="GridView1_RowUpdating">


                                   Page 2 of 9
              <Columns>
                  <asp:BoundField DataField="Productid" HeaderText="Productid"
ReadOnly />
                   <asp:BoundField DataField="Brand" HeaderText="Brand"
ReadOnly/>
                      <asp:BoundField DataField="Price" HeaderText="Price" ReadOnly />
                      <asp:BoundField DataField="Quantity" HeaderText="Quantity" />
                </Columns>
          </asp:GridView>
     </div>
     <asp:Button ID="Button1" runat="server" Text="Calculate"
          onclick="Button1_Click" />
     <asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>
     <br />
     <asp:Button ID="Button2" runat="server" PostBackUrl="~/Default.aspx"
          Text="GoBack" />
     </form>
</body></html>
                                     Default2.aspx.cs
public partial class Default2:System.Web.UI.Page {
     protected void Page_Load(object sender,EventArgs e) {
          if(!IsPostBack) {
                GridView1.DataSource=(List<CartItem>)Session["cart"];
                GridView1.DataBind();
          }
     }
   protected void GridView1_RowDeleting(object sender,GridViewDeleteEventArgs e) {
          int rid=e.RowIndex;
          List<CartItem> list=(List<CartItem>)Session["cart"];
          list.RemoveAt(rid);
          GridView1.DataSource=(List<CartItem>)Session["cart"];
          GridView1.DataBind();
     }
     protected void GridView1_RowEditing(object sender,GridViewEditEventArgs e) {
          this.GridView1.EditIndex=e.NewEditIndex;
          GridView1.DataSource=(List<CartItem>)Session["cart"];
          GridView1.DataBind();
     }
protected void GridView1_RowUpdating(object sender,GridViewUpdateEventArgs e) {
          List<CartItem> list=(List<CartItem>)Session["cart"];
          CartItem c=list[e.RowIndex];
          TextBox t=(TextBox)(GridView1.Rows[e.RowIndex].Cells[4].Controls[0]);
          c.Quantity=Convert.ToInt32(t.Text);
          this.GridView1.EditIndex=-1;


                                     Page 3 of 9
        GridView1.DataSource=(List<CartItem>)Session["cart"];
        GridView1.DataBind();
     }
     protected void GridView1_RowCancelingEdit(object
sender,GridViewCancelEditEventArgs e) {
          e.Cancel=true;
          this.GridView1.EditIndex=-1;
          GridView1.DataSource=(List<CartItem>)Session["cart"];
          GridView1.DataBind();
     }
     protected void Button1_Click(object sender,EventArgs e) {
          double sum=0;
          foreach(GridViewRow gvr in GridView1.Rows) {
                double price=Convert.ToDouble(gvr.Cells[3].Text);
                int quan=Convert.ToInt32(gvr.Cells[4].Text);
                sum+=price*quan;
          }
          Label1.Text=sum.ToString();
     }
}
                                    PersonCount.aspx.cs
public partial class PersonCount:System.Web.UI.Page {
     protected void Page_Load(object sender,EventArgs e) {
          if(Session["user"]==null) {
                Application.Lock();
                Application["count"]=(int)Application["count"]+1;
                Application.UnLock();
          }
          if(!IsPostBack) {
                if(Session["user"]==null) Session["user"]=User;
          }Label1.Text=Application["count"].ToString();
     }
}
                                         ViewState
public partial class ViewState:System.Web.UI.Page {
     protected void Page_Load(object sender,EventArgs e) {        }
     /*View State Lable1.EnableViewState=false Lable2.EnableViewState=true */
     protected void Button1_Click(object sender,EventArgs e) {
          Label1.Text=(Convert.ToInt32(Label1.Text)+1).ToString();
     }
     protected void Button2_Click(object sender,EventArgs e) {
          Label2.Text=(Convert.ToInt32(Label2.Text)+1).ToString();
     }
}


                                   Page 4 of 9
                                Validation Server Controls

A Validation server control is used to validate the data of an input control. If the data does not
pass validation, it will display an error message to the user.

RequirefieldValidator
Makes an input control a required field. With this control, the validation fails if the input value
does not change from its initial value
          <asp:RequiredFieldValidator                              id="RequiredFieldValidator1"
ControlToValidate="Text1" Font-Names="Arial" Font-Size="11" runat="server">
              Required field!
          </asp:RequiredFieldValidator>

RangeValidator
The RangeValidator control tests whether an input value falls within a given range.
RangeValidator uses three key properties to perform its validation: ControlToValidate contains
the value to validate, MinimumValue defines the minimum value of the valid range, and
MaximumValue defines the maximum value of the valid range. These constants are stored as
string values, but are converted to the data type defined by Type when the comparison is
performed.
<%@ Page clienttarget=downlevel %>
<html>
<head>
     <script language="C#" runat="server">
          void Button1_Click(Object sender, EventArgs e) {
               rangeValInteger.Validate();
               if (rangeValInteger.IsValid) lblOutput1.Text = "Result: Valid!";
               else lblOutput1.Text = "Result: Not Valid!";
               rangeValDate.Validate();
               if (rangeValDate.IsValid) lblOutput2.Text = "Result: Valid!";
               else lblOutput2.Text = "Result: Not Valid!";
               rangeValString.Validate();
               if (rangeValString.IsValid) lblOutput3.Text = "Result: Valid!";
               else lblOutput3.Text = "Result: Not Valid!";
               if (Page.IsValid) lblOutput.Text = "Result: Page Valid!";
               else lblOutput.Text = "Result: Page Not valid!";
          }
    </script>
      <asp:RangeValidator id="rangeValString" Type="String" ControlToValidate="txtComp3"
          MaximumValue="Zebra" MinimumValue="Aardvark" runat="server"/>

RegularExpressionValidator
The RegularExpressionValidator control confirms that the entry matches a pattern defined by a
regular expression. This type of validation allows you to check for predictable sequences of
characters, such as those in social security numbers, e-mail addresses, telephone numbers,
postal codes, and so on.



                                           Page 5 of 9
RegularExpressionValidator uses two key properties to perform its validation: ControlToValidate
contains the value to validate, and ValidationExpression contains the regular expression to
match.
<html><head>
    <script language="C#" runat=server>
         void ValidateBtn_Click(Object Src, EventArgs E) {
              if (Page.IsValid) lblOutput.Text = "Page is Valid!";
              else lblOutput.Text = "Page is InValid! :-(";
         }
   </script></head><body>
            <asp:RegularExpressionValidator id="RegularExpressionValidator1"
runat="server"
                   ControlToValidate="TextBox1" ValidationExpression="\d{5}"
                   Display="Static" Font-Names="verdana" Font-Size="10pt">
                      Zip code must be 5 numeric digits
            </asp:RegularExpressionValidator>

CompareValidator
The CompareValidator control compares the value of one control to another, or to an explicit
value in the control's ValueToCompare property.
CompareValidator uses three key properties to perform its validation. ControlToValidate and
ControlToCompare contain the values to compare. Operator defines the type of comparison to
perform, for example, Equal or Not Equal. CompareValidator performs the validation by
evaluating these properties as an expression, as shown in the following example.
<%@ Page clienttarget=downlevel %>
<html><head>
     <script language="C#" runat="server">
           void Button1_OnSubmit(Object sender, EventArgs e) {
                if (Page.IsValid) lblOutput.Text = "Result: Valid!";
                else lblOutput.Text = "Result: Not valid!";
           }
           void lstOperator_SelectedIndexChanged(Object sender, EventArgs e) {
                comp1.Operator = (ValidationCompareOperator) lstOperator.SelectedIndex;
                comp1.Validate();
           }
    </script>
        <asp:CompareValidator id="comp1" ControlToValidate="txtComp" ControlToCompare
= "txtCompTo" Type="String" runat="server"/>

CustomValidator
The CustomValidator control calls a user-defined function to perform validations that the
standard validators can't handle. The custom function can execute on the server or in client-side
script, such as JScript or VBScript. For client-side custom validation, the name of the custom
function must be identified in the ClientValidationFunction property. The custom function must
have the form function myvalidator(source, arguments) Note that source is the client-side
CustomValidator object, and arguments is an object with two properties, Value and IsValid. The
Value property is the value to be validated and the IsValid property is a Boolean used to set the


                                          Page 6 of 9
return result of the validation
For server-side custom validation, place your custom validation in the validator's
OnServerValidate delegate.
<html><head>
     <script language="C#" runat=server>
          void ValidateBtn_OnClick(object sender, EventArgs e) {
                 if (Page.IsValid) lblOutput.Text = "Page is valid!";
                 else lblOutput.Text = "Page is not valid! :-(";
          }
     void ServerValidate (object source, ServerValidateEventArgs value) {
          int num;
          if (int.TryParse(value.Value, out num) ) value.IsValid = (num % 2 == 0);
          else value.IsValid = false;
     }
    </script>
     <asp:CustomValidator id="CustomValidator1" runat="server" ControlToValidate="Text1"
          OnServerValidate="ServerValidate" Display="Static" Font-Names="verdana"
Font-Size="10pt"> Not an even number!
     </asp:CustomValidator>

ValidationSummary
When the user's input is processed (for example, when the form is submitted), the Web Forms
framework passes the user's entry to the associated validation control or controls. The validation
controls test the user's input and set a property to indicate whether the entry passed the
validation test. After all validation controls have been processed, the IsValid property on the
page is set; if any of the controls shows that a validation check failed, the entire page is set to
invalid.
A ValidationSummary control is displayed when the IsValid property of the page is false. It
"polls" each of the validation controls on the page and aggregates the text messages exposed by
each. The following sample illustrates displaying errors with a ValidationSummary
<%@ Page clienttarget=downlevel %>
<html><head>
      <script language="C#" runat=server>
           void ListFormat_SelectedIndexChanged(Object Sender, EventArgs E ) {
                 valSum.DisplayMode = (ValidationSummaryDisplayMode)
ListFormat.SelectedIndex;
           }
    </script>
</head><body>
<h3><font face="Verdana">ValidationSummary Sample</font></h3>
                 <asp:RequiredFieldValidator id="RequiredFieldValidator1"
                      ControlToValidate="RadioButtonList1" ErrorMessage="Card Type. "
                      Display="Static" InitialValue="" Width="100%" runat=server>
                 </asp:RequiredFieldValidator>
                 <asp:ValidationSummary ID="valSum" runat="server"
                      HeaderText="You must enter a value in the following fields:"
                      Font-Names="verdana" Font-Size="12" />



                                           Page 7 of 9
                                         基础概念
1.AutoPostback:
这是一个关于 textbox 的属性,如果设 autopostback 为 true,那么当我填写完后,切换到另外一
个操作的时候,所填写的将自动提交.
即:This will trigger a form submit immerdiately after use enter a new value and press <Enter>
key in the field.
但是如果在 Page_Load 里面设置为 if(!IsPostBack)的话
即:if (!IsPostBack) { Label1.Text = TextBox1.Text.ToString();
                Label2.Text = TextBox2.Text.ToString(); }
那么即使TextBox1设置autopostback为true,当你填写完之后,也不会提交!
2.PreviousPage:
这里的 findcontrol 是系统自带的,但是主要看你找的是什么控件,所以前面的 Label 是根据情
况而定,Label2 是 previouspage 中的一个 Label 的名字.
 if (PreviousPage != null) {
       Label1.Text = ((Label)PreviousPage.FindControl("Label2")).Text.ToString();
       Label2.Text = "My first page is not null!"; }
即:At the destination page,Method FindControl(“controlname”) can be used to read the control
value of the previous page Properties “PreviousPage” returns the Pages object that represents
the previous page.
3.IsPostBack:
所谓的postback即是是否提交,当我们进行一些datagrid改变的时候,有一些控件是自动提交
的,即会刷新页面,但我们有时并不需要立马就进行提交,所以我们用!IsPostBack去进行控制.
即:When this page is not loaded during a postback operation(i.e. brand new requst) update
datagrid with new data. else If this page is loaded during a postback operation, do not refresh
the datagrid.
4.Application and Session
 (1).User A access the internet application
      Application starts up
      Session starts up
 (2).User B access the internet application
      Since the application is already running
      Only session starts up
 (3).Application will only end after the both user A and B sessions end
Application: when the internet application is first started due to a user.
              Happens only once.
Session: whenever a user commences request for a page within an application
              Happens every time a new user access the web pages
5.Panel and PlaceHolder
Same function ,as a container for web-server controls created dynamically .
Placeholder is not displayed
Panel is not displayed
6.ViewState
如果在pageload里面设置为!postback的话,并且将Label的属性enableviewstate设置为false的
话,那么刷新的时候,label不会记得在pageload里面的设置
即:label is set to false, can not remember previous setting.




                                         Page 8 of 9
                                  Good and Bad Things
Good things
   1. Not so many unnecessary multimedia
            Response time not affected
   2. Logo is clickable to home page.
   3. Navigate using “click text” only allowing faster access.
   4. Everything fits on one page on Main page.
   5. Use of drop down menus allow space saving.
   6. Pop up dictionary for non native English speakers.
   7. Latest news is advertised.
   8. Breadcrumbs available for knowing where you are.

Bad Things
   1. No site map path available
   2. Links are duplicated eg. About us and ontact us
   3. Cluttered site and layout is complicated
   4. Suggest similar page




                                          Page 9 of 9

								
To top