A Simple Example of Shopping Cart With Ajax and ASP.Net

In this example, we will use a DropDownList, Label and TextBox to show our data. Here we will use an Ajax UpdatePanel (in order to prevent refresh and PostBack).

Here we first create two DropDownlists for Category and Product, and then we will create two Label Controls for Price and SubTotal and then a TextBox control for the Quantity. So when we select the Category, the other DropDownlist Product will add some Products depending on that Category and when we select the Product, the Label (Price and SubTotal) and TextBox (Qunatity) will get the values depending on the Product. And when we change the Quantity, The SubTotal will be changed depending on the value of Quantity.

Shopping Cart in ASP.NET

Step 1: First we create the Database like this:

create database CartEx
use CartEx 
create table Cart
(
    id int identity(1,1),
   
Category varchar(100),
   
Product varchar(100),
   
Price decimal(8,3),
    Qunatity varchar(10),
    SubTotal decimal(8,5) default 0
)

Step 2: In the .aspx page we will add the ScriptManager and UpdatePanel like this:

<asp:ScriptManager ID="ScriptManager1" runat="server">
</
asp:ScriptManager>
<
asp:UpdatePanel ID="UpdatePanel1" runat="server">
</
asp:UpdatePanel>

Step 3: Now we will add two DropDownlists, one for Category and another one for Product like this:

<
asp:UpdatePanel ID="UpdatePanel1" runat="server">
     <ContentTemplate>
          <table id="table1" runat="server">
              <tr>
                  <td id="td1" runat="server" style="font-weight: 700; color: #800000; font-family: Andalus"
                      class="style1">Category</td>
                  <td class="style1">&nbsp;&nbsp;&nbsp;
                      <asp:DropDownList ID="ddlCategory" runat="server" AutoPostBack="true" OnSelectedIndexChanged="Category_Changed">
                      </asp:DropDownList>
                      &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
                  </td>
                  <td>&nbsp;&nbsp;</td>
                  <td style="font-weight: 700; color: #800000; font-family: Andalus"
                      class="style1">&nbsp; Product:</td>
                  <td class="style1">
                     <asp:DropDownList ID="ddlProduct" runat="server" AutoPostBack="true"">
                     </asp:DropDownList>
                 </td>
             </tr>
         </table>
     </ContentTemplate>
</
asp:UpdatePanel>

Step 4: Now we will write the code to fill the data in the Category DropDownList as in the following:

protected void Page_Load(object sender, EventArgs e)
{
    if (!IsPostBack)
    {
         Bind();
    }      
}
 
protected void Bind()
{
    ddlCategory.Items.Insert(0, new ListItem("Select Category", "0"));          
    con.Open();
    SqlCommand cmd = new SqlCommand("select distinct Category from Cart", con);
    SqlDataReader dr = cmd.ExecuteReader();
    while (dr.Read())
    {
         ddlCategory.Items.Add(dr["Category"].ToString()); 
    }
    con.Close();       
}

Step 5: Now we will write the code to fill in the data in the Product DropDownList as in the following:

protected void Category_Changed(object sender, EventArgs e)
{         
     ddlProduct.Items.Clear(); 
     ddlProduct.Items.Insert(0, new ListItem("Select Product", "0"));        
     con.Open();
     SqlCommand cmd = new SqlCommand("select distinct Product from Cart where Category='" + ddlCategory.SelectedItem.Text + "'", con);
     SqlDataReader dr = cmd.ExecuteReader();
     while (dr.Read())
     {
          ddlProduct.Items.Add(dr["Product"].ToString());
     }
     con.Close();          
}


So when we click on the Catgory the Product List will be changed depending on that Category like this:

Shopping cart Product List

Step 6: Now we will write the code to get the value of Quantity, Price and Subtotal from the database.

protected void Product_Changed(object sender, EventArgs e)
{       
    con.Open();
    SqlCommand cmd = new SqlCommand("select * from Cart where Product='" + ddlProduct.SelectedItem.Text + "'", con);
    SqlDataReader dr = cmd.ExecuteReader();
    while (dr.Read())
    {
         lblPrice.Text = dr["Price"].ToString();
         txtQunatity.Text = dr["Qunatity"].ToString();
         lblSubTotal.Text = Convert.ToString(Convert.ToDecimal(lblPrice.Text) * Convert.ToInt32(txtQunatity.Text));
    }
    con.Close();       
}

So when we select the Product, the value of Quantity, Price and SubTotal will change depedning on the Product like this:

select item from shopping cart

Step 7: Now we will write the code to change the value of SubTotal depending on the Quantity:

protected void txtQunatity_TextChanged(object sender, EventArgs e)
{     
    if (txtQunatity.Text == "")
    {
    }
    else
    {
        lblSubTotal.Text = Convert.ToString(Convert.ToDecimal(lblPrice.Text) * Convert.ToInt32(txtQunatity.Text));
    }
}

So when we change the value of Quantity the value of SubTotal will be changed like this:

Shopping Cart price

Step 8: Now we will write the code for the Add Button, since the data of Category, Product and Price are already saved in the database, so here we will update only the Quantity and Price and show the data in the GridView:

protected void btnAdd_Click(object sender, EventArgs e)
{
    ddlCategory.Items.Clear();
    Bind(); 
    CalculateTotal();
    con.Open();
    SqlCommand cmd2 = new SqlCommand("update Cart Set Qunatity='" + txtQunatity.Text + "',SubTotal='" + lblSubTotal.Text + "' where Product='" + ddlProduct.SelectedItem.Text + "'", con);
    cmd2.ExecuteNonQuery();
    con.Close();
    BindGridView();
}

Step 9: Now we will calulate the Total:

protected void CalculateTotal()
{
     con.Open();
     SqlCommand cmd1 = new SqlCommand("select * from Cart", con);
     SqlDataReader dr = cmd1.ExecuteReader();      
     while (dr.Read())
     {
          if (dr["Subtotal"] != "")
             Total = Total + Convert.ToDecimal(dr["Subtotal"].ToString());
     }
     lblTotal.Text = Convert.ToString(Total);
     con.Close();
}

Step 10: Now we will write the code for the Delete Button of the GridView:

protected void gvCart_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
     Label lblId = gvCart.Rows[e.RowIndex].FindControl("lblId") as Label;
     Int32 id = Convert.ToInt32(lblId.Text);
     con.Open();
     SqlCommand cmd = new SqlCommand("update Cart set SubTotal='0',Qunatity='1' where id="+id+"", con);
     cmd.ExecuteNonQuery();
     con.Close();
     BindGridView();
     con.Open();
     SqlCommand cmd1 = new SqlCommand("select * from Cart", con);
     SqlDataReader dr = cmd1.ExecuteReader();
     Total =Convert.ToDecimal(0.0);
     while (dr.Read())
     {
         if (dr["Subtotal"] != "")
             Total = Total + Convert.ToDecimal(dr["Subtotal"].ToString());
     }
     lblTotal.Text = Convert.ToString(Total);
     con.Close();  
}

Up Next
    Ebook Download
    View all
    Learn
    View all