C# 在ASP.NET中为购物车系统创建数量更新按钮

C# 在ASP.NET中为购物车系统创建数量更新按钮,c#,asp.net,.net,visual-studio-2012,C#,Asp.net,.net,Visual Studio 2012,我正在asp.net中为购物车系统创建更新按钮。我试图做的是允许用户输入数量项目,然后单击更新按钮。这里是购物车系统的设计 不幸的是,更新按钮在第一行之后不能正常工作。我已经调试了这个问题,btn\u update\u Click方法中的for循环返回零值 有没有其他办法克服这个问题?谢谢 以下是源代码: <b><asp:Label ID="lbl_showResult" runat="server" Text=""></asp:Label></b&g

我正在asp.net中为购物车系统创建更新按钮。我试图做的是允许用户输入数量项目,然后单击更新按钮。这里是购物车系统的设计

不幸的是,更新按钮在第一行之后不能正常工作。我已经调试了这个问题,btn\u update\u Click方法中的for循环返回零值

有没有其他办法克服这个问题?谢谢

以下是源代码:

<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" /> 




下面是.cs的另一个源代码:

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

    }
}
使用系统;
使用System.Collections.Generic;
使用系统配置;
使用System.Data.SqlClient;
使用系统诊断;
使用System.Linq;
使用System.Text.RegularExpressions;
使用System.Web;
使用System.Web.UI;
使用System.Web.UI.WebControl;
名称空间网站
{
公共部分类购物车:System.Web.UI.Page
{
//打开sql数据库的连接
专用静态连接连接;
私有静态SqlCommand;
受保护的无效页面加载(对象发送方、事件参数e)
{
//为数据库的连接创建一个实例
string connectionString=ConfigurationManager.connectionString[“websiteConnection”].ToString();
conn=新的SqlConnection(connectionString);
命令=新的SqlCommand(“,conn);
//检查购物车数据库中有多少项目,并将其显示在标签上
检查howmanyItem();
//把所有的费用加起来
lbl_totalCost.Text=“总成本:$”+TotalProductCost().ToString();
}
//检查购物车数据库中有多少项目,并将其显示在标签上
public void CheckHowManyItem()
{
尝试
{
conn.Open();
//从数据库中检索行数
string query=string.Format(“从tbl_购物车中选择COUNT(*),其中name='{0}',visible='{1}',Session[“login”],“true”);
command.CommandText=查询;
int numberOfItems=(int)command.ExecuteScalar();
//如果行数为零
如果(numberOfItems==0)
{
lbl_showResult.Text=“购物车中没有任何物品。”;
btn_buy.Visible=false;
}
其他的
{
//如果里面有行数
lbl_showResult.Text=“购物车中当前有“+numberOfItems+”;
btn_buy.Visible=true;
}
}
最后
{
康涅狄格州关闭();
}
}
受保护的无效btn\u删除\u单击(对象发送方,事件参数e)
{
//从ASP.NET gridview按钮获取值
按钮btn=(按钮)发送器;
尝试
{
conn.Open();
//如果id与网格视图数据源匹配,则使购物车不可见
string query=string.Format(“更新tbl_购物车集可见='{0}',其中id='{1}'”,“false”,btn.CommandArgument);
command.CommandText=查询;
command.ExecuteNonQuery();
重定向(“cart.aspx”);
}
最后
{
康涅狄格州关闭();
}
}
//将所有购买的价值相乘
公共int TotalProductCost()
{
整数总成本=0;
int currentCost=0;
int currentQuantity=0;
对于(int i=0;i<asp:GridView ID="grv_cart" runat="server" AllowPaging="True" 
    AutoGenerateColumns="False" DataSourceID="sds_store" ShowHeader="True" 
    GridLines="None" CssClass="table" OnRowCommand="grv_cart_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();
    }
}
<asp:Button ID="btn_update" Text="Update" runat="server" 
    CommandArgument='<%# Eval("id") %>' CssClass="btn btn-warning" />