title: Creating the quantity update button for Cart System in ASP.NET
body: <p>I am creating the update button for the cart system in asp.net. What am I trying to do is to allow user key in the quantity items and then click the update button. Here is the design of the shopping cart system...</p>
  
  <p><img src="https://i.stack.imgur.com/Xi3qq.png" alt="enter image description here"></p>
  
  <p>Unfortunately the update button doesn't work properly <strong>after the first row</strong>. I have debugged the problem and the for loop inside the <strong>btn_update_Click</strong> method returns the value of zero.</p>
  
  <p>Is there any other way to overcome the problem? Thanks</p>
  
  <p>Here is the source code:</p>
  
  <pre><code>&lt;b&gt;&lt;asp:Label ID="lbl_showResult" runat="server" Text=""&gt;&lt;/asp:Label&gt;&lt;/b&gt;
  
                  &lt;asp:GridView ID="grv_cart" runat="server" AllowPaging="True" AutoGenerateColumns="False" DataSourceID="sds_store" ShowHeader="True" GridLines="None" CssClass="table"&gt;
  
                      &lt;Columns&gt;
                          &lt;asp:TemplateField&gt;                      
                              &lt;ItemTemplate&gt;                        
                                  &lt;a class="hyp_productimage imgLiquidFill imgLiquid productImage img-responsive" href='&lt;%# string.Format("product.aspx?ProductID={0}", Eval("product_id")) %&gt;'&gt;
                                      &lt;img src='&lt;%#Eval("image") %&gt;' /&gt;
                                  &lt;/a&gt; 
                              &lt;/ItemTemplate&gt;
                          &lt;/asp:TemplateField&gt;
  
                          &lt;asp:TemplateField HeaderText="Product"&gt;
                              &lt;ItemTemplate&gt;
                                  &lt;asp:Hyperlink ID="hyp_productname" Text='&lt;%# Eval("product_name") %&gt;' runat="server" NavigateUrl='&lt;%# string.Format("product.aspx?ProductID={0}", Eval("product_id")) %&gt;'&gt;&lt;/asp:Hyperlink&gt;
                              &lt;/ItemTemplate&gt;
                          &lt;/asp:TemplateField&gt;
  
                          &lt;asp:TemplateField HeaderText="Quantity"&gt;
                              &lt;ItemTemplate&gt;
                                  &lt;asp:TextBox ID="txt_productQuantity" Text='&lt;%# Eval("product_quantity") %&gt;' CssClass="form-control" runat="server" Width="60" MaxLength="5"&gt;&lt;/asp:TextBox&gt; 
                              &lt;/ItemTemplate&gt;
                          &lt;/asp:TemplateField&gt;
  
                          &lt;asp:TemplateField&gt;
                              &lt;ItemTemplate&gt;                                                                     
                                  &lt;asp:Button ID="btn_update" Text="Update" runat="server" CommandArgument='&lt;%# Eval("id") %&gt;' CssClass="btn btn-warning" OnClick="btn_update_Click" /&gt;
                                  &lt;asp:Button ID="btn_remove" Text="Delete" runat="server" CommandArgument='&lt;%# Eval("id") %&gt;' CssClass="btn btn-danger" onclick="btn_remove_Click"/&gt;                                                                
                              &lt;/ItemTemplate&gt;
                          &lt;/asp:TemplateField&gt;                  
  
                          &lt;asp:TemplateField HeaderText="Cost"&gt;
                              &lt;ItemTemplate&gt;
                                  &lt;asp:Hyperlink ID="hyp_productcost" Text='&lt;%#"$"+Eval("product_cost") %&gt;' runat="server" NavigateUrl='&lt;%# string.Format("product.aspx?ProductID={0}", Eval("product_id")) %&gt;'&gt;&lt;/asp:Hyperlink&gt;
                              &lt;/ItemTemplate&gt;
                          &lt;/asp:TemplateField&gt;                           
  
                      &lt;/Columns&gt;
  
                  &lt;/asp:GridView&gt;
                  &lt;asp:SqlDataSource ID="sds_store" runat="server" 
                      ConnectionString="&lt;%$ ConnectionStrings:websiteConnection %&gt;" 
                      SelectCommand="SELECT [id], [product_id], [product_name], [product_cost], [product_description], [product_quantity], [image], [date] FROM [tbl_cart] WHERE [name] = @username AND [visible] = @visible"&gt;
  
                      &lt;SelectParameters&gt;
                          &lt;asp:sessionparameter sessionfield="login" Name="username" /&gt;
                          &lt;asp:Parameter Name="visible" Type="string" DefaultValue="true" /&gt;
                      &lt;/SelectParameters&gt;
                  &lt;/asp:SqlDataSource&gt;
  
                  &lt;h4&gt;&lt;asp:Label ID="lbl_totalCost" Text="" runat="server" CssClass="pull-right"&gt;&lt;/asp:Label&gt;&lt;/h4&gt;
                  &lt;br /&gt;&lt;br /&gt;&lt;br /&gt;
                  &lt;asp:Button ID="btn_buy" Text="Buy Now" runat="server" CssClass="btn btn-success btn-lg pull-right" OnClick="btn_buy_Click" /&gt; 
  </code></pre>
  
  <p>Here's another source code for the .cs:</p>
  
  <pre><code>using System;
  using System.Collections.Generic;
  using System.Configuration;
  using System.Data.SqlClient;
  using System.Diagnostics;
  using System.Linq;
  using System.Text.RegularExpressions;
  using System.Web;
  using System.Web.UI;
  using System.Web.UI.WebControls;
  
  namespace websiteEcom
  {
      public partial class cart : System.Web.UI.Page
      {
          // Open the connection for the sql
          private static SqlConnection conn;
          private static SqlCommand command;
  
          protected void Page_Load(object sender, EventArgs e)
          {
              // Create an instance for the connection of database
              string connectionString = ConfigurationManager.ConnectionStrings["websiteConnection"].ToString();
              conn = new SqlConnection(connectionString);
              command = new SqlCommand("", conn);
  
              // Checks how many items are there inside the cart database and display it to the label 
              CheckHowManyItem();
  
              // Multiply all the sums of the cost
              lbl_totalCost.Text = "Total Cost: $"+TotalProductCost().ToString();
  
          }
  
          // Checks how many items are there inside the cart database and display it to the label 
          public void CheckHowManyItem()
          {
              try
              {
                  conn.Open();
  
                  // Retrieve the number of rows from the database
                  string query = string.Format("SELECT COUNT(*) FROM tbl_cart WHERE name = '{0}' AND visible = '{1}'", Session["login"], "true");
                  command.CommandText = query;
                  int numberOfItems = (int)command.ExecuteScalar();
  
                  // If the number of rows is zero
                  if (numberOfItems == 0)
                  {
                      lbl_showResult.Text = "You have no items inside the cart.";
                      btn_buy.Visible = false;
                  }
                  else
                  {
                      // If there is number of rows inside
                      lbl_showResult.Text = "There are currently " + numberOfItems + " inside the cart.";
                      btn_buy.Visible = true;
                  }
              }
              finally
              {
                  conn.Close();
              }
          }
  
  
          protected void btn_remove_Click(object sender, EventArgs e)
          {
              // Get the value from the button ASP.NET gridview
              Button btn = (Button)sender;
  
              try
              {
                  conn.Open();
  
                  // Make the cart invisible if the id matches with the grid view data source
                  string query = string.Format("UPDATE tbl_cart SET visible = '{0}' WHERE id = '{1}'", "false", btn.CommandArgument);
                  command.CommandText = query;
                  command.ExecuteNonQuery();
  
                  Response.Redirect("cart.aspx");
              }
              finally
              {
                  conn.Close();
              }
  
          }
  
  
          // Multiply all the values of purchases together
          public int TotalProductCost()
          {
              int totalCost = 0;
              int currentCost = 0;
              int currentQuantity = 0;
  
              for (int i = 0; i &lt; grv_cart.Rows.Count; i++)
              {
                  // Get the data values from the forms
                  HyperLink hypCost = (HyperLink)grv_cart.Rows[i].Cells[0].FindControl("hyp_productcost");
                  TextBox txtQuantity = (TextBox)grv_cart.Rows[i].Cells[0].FindControl("txt_productQuantity");
  
                  // Sum the product quantity and the product cost               
                  // Attempt to parse your value (removing any non-numeric values)
                  currentQuantity = Int32.Parse(Regex.Replace(txtQuantity.Text, @"[^\d]", ""));               
  
                  // Attempt to parse your value (removing any non-numeric values)
                  currentCost = Int32.Parse(Regex.Replace(hypCost.Text, @"[^\d]", ""));
  
                  currentCost *= currentQuantity;
  
                  totalCost += currentCost;
  
  
              }
              return totalCost;
  
          }
  
          protected void btn_buy_Click(object sender, EventArgs e)
          {
  
  
          }
  
  
          protected void btn_update_Click(object sender, EventArgs e)
          {
              // Get the value from the button ASP.NET gridview
              Button btn = (Button)sender;
  
              foreach (GridViewRow grvCart in grv_cart.Rows)
              {
                  Debug.WriteLine(btn.CommandArgument);
  
                  TextBox textQuantity = (TextBox)grvCart.FindControl("txt_productQuantity");
                  int currentQuantity = Int32.Parse(Regex.Replace(textQuantity.Text, @"[^\d]", ""));
  
                  try
                  {
                      conn.Open();
  
                      // Update the cart quantity if the id matches with the grid view data source
                      string query = string.Format("UPDATE tbl_cart SET product_quantity = '{0}' WHERE id = '{1}'", currentQuantity, btn.CommandArgument);
                      command.CommandText = query;
                      command.ExecuteNonQuery();
  
                      Response.Redirect("cart.aspx");
                  }
                  finally
                  {
                      conn.Close();
                  }
              }
          }
  
      }
  }
  </code></pre>