【问题标题】:Updating database with dynamically created textbox使用动态创建的文本框更新数据库
【发布时间】:2013-03-14 08:36:03
【问题描述】:

我正在为我拥有的网页项目编写购物车功能。在购物车页面上,它会在 cookie 中检查您的购物车 ID,然后在数据库中获取您的所有商品。因此,Cart 表中的每个项目都是动态创建的。在 .aspx 页面上,创建了一个空表。在代码隐藏中,为每个项目创建一个新行和单元格。

我在更新某个商品的数量时遇到问题。对于购物车中的每个项目,都会为数量动态创建一个文本框和按钮,并更新数量。数量设置为页面加载时数据库中的任何数量。在文本框被更改后,我似乎无法获取文本框的值,例如从 1 到 2。

以下是表格填充方式的摘要。我已经缩短了很多,只是为了展示我如何将数据加载到表中。

protected void Page_Load(object sender, EventArgs e){
    cartpopulate(cartID);
}

private void cartpopulate(int cartID){
    //for each item in database where cartID is paramater cartID
    //create a row 
    //get the product name, image, price, quantity, options, and make a cell for each
    //calculate total price from quantity and price
    //add in delete and quantity update buttons

为方便起见,我们假设所有数量都是 1。因此,在 page_load 上,它将所有数量设置为 1。我认为我的问题是以下代码将文本框的值设置为任何数量当它被填充时,这将是 1。当您将其更改为 2 或其他值时,该值已经设置并且 2 什么都不做。数据库更新部分有效,我只是无法获得第二个值“2”。

这是数量更新代码...

            if (prod.Quantity == null) { quantitylabel.Value = 1.ToString(); }
            else { quantitylabel.Value = prod.Quantity.ToString() ; }
            quantityinput.ID = "quantity" + i.ToString();
            quantityinput.Width = 20;
            quantityinput.Text = quantitylabel.Value.ToString();
            quantitycell.Controls.Add(quantityinput);
            quantitycell.CssClass="cartitem";
            row.Cells.Add(quantitycell);

            Button btnUpdate = new Button();
            btnUpdate.Text = "Update";
            string arg = quantityinput.Text;
            btnUpdate.CommandName = "update";
            btnUpdate.CommandArgument = arg;
            btnUpdate.Command += (s, e) =>
                {
                    string quanupdate = Convert.ToString(e.CommandArgument);
                    int quanint = Convert.ToInt32(quanupdate);
                    prod.Quantity = quanint;
                    db.SubmitChanges();
                    Response.Redirect("cart.aspx");
                };

我查看了一些不同的解决方案,但似乎没有一个有效。我怀疑的两件事是问题将在 !IsPostBack 上做某事,或者在回发时重新创建动态创建的控件。我在网络编程方面是自学成才的,所以我不能 100% 确定如何做到这一点,但我认为其中之一就是问题所在。

提前致谢

【问题讨论】:

    标签: c# asp.net linq dynamic textbox


    【解决方案1】:

    尝试使用静态变量,即使用 prod.Quantity 作为静态变量

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-12-28
      • 2021-03-27
      • 2014-08-13
      • 2020-09-02
      • 2012-11-25
      • 2013-02-01
      • 1970-01-01
      相关资源
      最近更新 更多