2013-11-21 3 views
2

asp.net의 카트 시스템에 대한 업데이트 버튼을 생성하고 있습니다. 내가하려는 것은 수량 항목에서 사용자 키를 허용 한 다음 업데이트 버튼을 클릭하는 것입니다. 여기에 쇼핑 카트 시스템의 설계 ... ASP.NET의 카트 시스템 수량 업데이트 버튼 만들기

enter image description here

불행하게도 업데이트 버튼을 첫 번째 행 후 제대로 작동하지 않습니다이다. 나는 문제를 디버깅하고 내부의 for 루프는 btn_update_Click 메서드는 0 값을 반환합니다.

문제를 극복하는 다른 방법이 있습니까? .cs 또 다른 소스 코드를 여기에

<b><asp:Label ID="lbl_showResult" runat="server" Text=""></asp:Label></b> 

       <asp:GridView ID="grv_cart" runat="server" AllowPaging="True" AutoGenerateColumns="False" DataSourceID="sds_store" ShowHeader="True" GridLines="None" CssClass="table"> 

        <Columns> 
         <asp:TemplateField>      
          <ItemTemplate>       
           <a class="hyp_productimage imgLiquidFill imgLiquid productImage img-responsive" href='<%# string.Format("product.aspx?ProductID={0}", Eval("product_id")) %>'> 
            <img src='<%#Eval("image") %>' /> 
           </a> 
          </ItemTemplate> 
         </asp:TemplateField> 

         <asp:TemplateField HeaderText="Product"> 
          <ItemTemplate> 
           <asp:Hyperlink ID="hyp_productname" Text='<%# Eval("product_name") %>' runat="server" NavigateUrl='<%# string.Format("product.aspx?ProductID={0}", Eval("product_id")) %>'></asp:Hyperlink> 
          </ItemTemplate> 
         </asp:TemplateField> 

         <asp:TemplateField HeaderText="Quantity"> 
          <ItemTemplate> 
           <asp:TextBox ID="txt_productQuantity" Text='<%# Eval("product_quantity") %>' CssClass="form-control" runat="server" Width="60" MaxLength="5"></asp:TextBox> 
          </ItemTemplate> 
         </asp:TemplateField> 

         <asp:TemplateField> 
          <ItemTemplate>                  
           <asp:Button ID="btn_update" Text="Update" runat="server" CommandArgument='<%# Eval("id") %>' CssClass="btn btn-warning" OnClick="btn_update_Click" /> 
           <asp:Button ID="btn_remove" Text="Delete" runat="server" CommandArgument='<%# Eval("id") %>' CssClass="btn btn-danger" onclick="btn_remove_Click"/>                 
          </ItemTemplate> 
         </asp:TemplateField>     

         <asp:TemplateField HeaderText="Cost"> 
          <ItemTemplate> 
           <asp:Hyperlink ID="hyp_productcost" Text='<%#"$"+Eval("product_cost") %>' runat="server" NavigateUrl='<%# string.Format("product.aspx?ProductID={0}", Eval("product_id")) %>'></asp:Hyperlink> 
          </ItemTemplate> 
         </asp:TemplateField>       

        </Columns> 

       </asp:GridView> 
       <asp:SqlDataSource ID="sds_store" runat="server" 
        ConnectionString="<%$ ConnectionStrings:websiteConnection %>" 
        SelectCommand="SELECT [id], [product_id], [product_name], [product_cost], [product_description], [product_quantity], [image], [date] FROM [tbl_cart] WHERE [name] = @username AND [visible] = @visible"> 

        <SelectParameters> 
         <asp:sessionparameter sessionfield="login" Name="username" /> 
         <asp:Parameter Name="visible" Type="string" DefaultValue="true" /> 
        </SelectParameters> 
       </asp:SqlDataSource> 

       <h4><asp:Label ID="lbl_totalCost" Text="" runat="server" CssClass="pull-right"></asp:Label></h4> 
       <br /><br /><br /> 
       <asp:Button ID="btn_buy" Text="Buy Now" runat="server" CssClass="btn btn-success btn-lg pull-right" OnClick="btn_buy_Click" /> 

것 : 여기

감사

는 소스 코드

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 < 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(); 
       } 
      } 
     } 

    } 
} 
+0

버튼을 가지고 있기 때문에 업데이트 이벤트에'foreach' 루프가 필요 없다고 생각합니다. 각 레코드에서 삭제 이벤트에서 수행하는 것과 동일한 행을 업데이트 할 수 있습니다. – Damith

+0

알겠습니다. – Minelava

답변

0

(이미 CommandArgument가 설정 한 특히 이후)에 RowCommand 이벤트를 사용해보십시오 . 이것이 바로 이러한 유형의 작업을 처리하는보다 적절한 방법입니다. 그리고 모든 방법을 반복하지 않고 한 번에 한 행씩 업데이트 할 수 있습니다.

<asp:GridView ID="grv_cart" runat="server" AllowPaging="True" 
    AutoGenerateColumns="False" DataSourceID="sds_store" ShowHeader="True" 
    GridLines="None" CssClass="table" OnRowCommand="grv_cart_RowCommand"> 

을 그리고 이벤트 핸들러는 다음과 같은 모습 일 것이다 :

당신의 GridView 선언에 RowCommand 이벤트를 처리

protected void grv_cart_RowCommand(Object sender, GridViewCommandEventArgs e) 
{ 
    GridViewRow rowToUpdate = grv_cart.Rows[Int.Parse(e.CommandArgument)]; 
    TextBox textQuantity = (TextBox)rowToUpdate.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, e.CommandArgument); 
     command.CommandText = query; 
     command.ExecuteNonQuery(); 
     Response.Redirect("cart.aspx"); 
    } 
    finally 
    { 
     conn.Close(); 
    } 
} 

참고 : 당신은에서의 OnClick 핸들러를 제거 할 수 있습니다 업데이트 버튼 :

<asp:Button ID="btn_update" Text="Update" runat="server" 
    CommandArgument='<%# Eval("id") %>' CssClass="btn btn-warning" /> 
+0

감사합니다. 그러나 주요 문제는 입력에 관한 것입니다. 이 메소드는 어떻게 트리거됩니까? – Minelava

+1

@Minelava GridView의 행 내에서 버튼 (asp : Button, asp : LinkButton 등)을 클릭하면이 메서드가 트리거됩니다. – jadarnel27

+0

아, 고마워. – Minelava

관련 문제