【问题标题】:Text box in gridview not auto post backgridview中的文本框不会自动回发
【发布时间】:2025-12-12 11:45:02
【问题描述】:

我的gridview 回发时缺少以前的数据。这是场景,当我从gvFinalisedgridview 检测到库存不足时,我得到了类别,然后我得到了库存最高的产品并显示在gvSuggestedgridview 中。

但是假设在我的gvFinalised,三个不同类别的三个产品是不够的,假设它们是面条,罐头食品和饮料。它应该在gvSuggested 中显示三种不同类别的最高库存产品。

但是,我现在的问题是,它只显示最后的项目。例如,在这种情况下,饮料。 Beverages 之前的数据刚刚被清除。

这是我如何检测库存不足的代码:

protected void tbQuantity_TextChanged(object sender, EventArgs e)
{
    tempList = new Dictionary<string, string>();
    distSPUItemList = new Dictionary<string, int>();
    bool valid = true;
    string quantityStr = "", prodID = "";
    int packagesNeeded = 0, totalUnit = 0, quantity = 0;

    //Get the total packages needed for this distribution
    packagesNeeded = prodPackBLL.getPackagesNeededByDistributionID(distributionID);

    foreach (GridViewRow gr in gvFinalised.Rows)
    {
        //Clear label error message
        Label lblCheckAmount = gr.FindControl("lblCheckAmount") as Label;
        lblCheckAmount.Text = "";

        //Get the product variant ID which set as DataKeyNames and product quantity from selected row index
        prodID = gvFinalised.DataKeys[gr.RowIndex].Value.ToString();

        var tbQuantity = gr.FindControl("tbQuantity") as TextBox;
        if (tbQuantity != null)
        {
            //Check if the input is numeric
            quantityStr = tbQuantity.Text;
            if (!int.TryParse(quantityStr, out quantity))
            {
                lblCheckAmount.Text = "Non-numeric input!";
                TextBox tb = (TextBox)gr.FindControl("tbQuantity") as TextBox;
            }
            else
            {
                //Add both objects into Dictionary
                tempList.Add(prodID, quantityStr);
            }
        }
    }

    //Portion to check the storage level for each products stored in tempList
    //Loop thru tempList. key as prod variant ID, tempList.Keys as quantity
    foreach (string key in tempList.Keys)
    {
        //Get total unit of each products
        totalUnit = prodPackBLL.getTotalProductUnit(key);
        valid = true;

        //Check if unitQuantity exceed storage level
        if (((Convert.ToInt32(tempList[key])) * packagesNeeded) > totalUnit)
        {
            //Get the label control in gridview
            foreach (GridViewRow gr in gvFinalised.Rows)
            {
                if (key == gvFinalised.DataKeys[gr.RowIndex].Value.ToString())
                {
                    //Change the color of textBox and display the insufficient message
                    valid = false;
                    //Automatically uncheck the checkBox if invalid
                    TextBox tb = (TextBox)gr.FindControl("tbQuantity") as TextBox;
                    Label lblCheckAmount = gr.FindControl("lblCheckAmount") as Label;
                    lblCheckAmount.Text = "Insufficient stock!";

                    //Here is the place where I collect the data and display in gvSuggested
                    getSuggested(key);
                }
            }
        }
        else
        {
            if (totalUnit - ((Convert.ToInt32(tempList[key])) * packagesNeeded) == 0)
            {

                foreach (GridViewRow gr in gvFinalised.Rows)
                {
                    if (key == gvFinalised.DataKeys[gr.RowIndex].Value.ToString())
                    {
                        valid = true;
                        Label lblCheckAmount = gr.FindControl("lblCheckAmount") as Label;
                        lblCheckAmount.Attributes["style"] = "color:#ffb848";
                        lblCheckAmount.Text = "Stock becomes 0!";
                    }
                }
            }
        }

        //Portion to check for valid products to be inserted into distSPUItemList
        if (valid)
        {
            //Set the textBox color
            foreach (GridViewRow gr in gvFinalised.Rows)
            {
                if (key == gvFinalised.DataKeys[gr.RowIndex].Value.ToString())
                {
                    TextBox tb = (TextBox)gr.FindControl("tbQuantity") as TextBox;
                }
            }
            //Validated items store into another list to perform Sql statement when button on click
            distSPUItemList.Add(key, (Convert.ToInt32(tempList[key]) * packagesNeeded));
        }
    }
}

这是填充我的gvSuggetedgetSuggested() 方法:

protected void getSuggested(string prodVariantID)
{
    string categoryName = prodPackBLL.getCategoryByProdVariantID(prodVariantID);

    //Get the list of substitute product with highest storage level  sorted in descending order
    List<ProductPacking> prodSubstitute = new List<ProductPacking>();
    List<string> lstCategory = new List<string>();
    List<string> prodIDList = new List<string>();
    List<DistributionStandardPackingUnitItems> distSPUItem = new List<DistributionStandardPackingUnitItems>();

    distSPUItem = this.SuggestedItems;

    //Find list of substitute with highest stock level and replace the product
    prodSubstitute = prodPackBLL.getProductIDWithHighestStock(categoryName);

    for (int count = 0; count < prodSubstitute.Count; count++)
    {
        //To prevent duplication of same product and select those catories which are in current category and counting them and taking them if there are less than 1 occurrences
        if (!prodIDList.Contains(prodSubstitute[count].id) && !(lstCategory.Where(x => x.Equals(categoryName)).Select(x => x).Count() >= 2))
        {
            prodIDList.Add(prodSubstitute[count].id);
            lstCategory.Add(categoryName);
        }
    }

    for (int j = 0; j < prodIDList.Count; j++)
    {
        //Get the detail of the product added into prodList and add it into distSPUItem List
        distSPUItem.Add(packBLL.getSPUItemDetailByID(prodIDList[j]));
    }

    gvSuggested.DataSource = distSPUItem;
    gvSuggested.DataBind();

    this.SuggestedItems = distSPUItem;
}

private List<DistributionStandardPackingUnitItems> SuggestedItems
{
    get
    {
        if (ViewState["SuggestedItems"] == null)
        {
            return new List<DistributionStandardPackingUnitItems>();
        }
        else
        {
            return (List<DistributionStandardPackingUnitItems>)ViewState["SuggestedItems"];
        }
    }
    set
    {
        ViewState["SuggestedItems"] = value;
    }
}

我在回发时使用viewState 来存储数据。但是,它不起作用。 gvSuggested 中的这一行:

this.SuggestedItems = distSPUItem; 

导致我在 gridView 中的文本框不能自动回发。如果我删除它,上面的错误会再次出现。任何指南?提前致谢。

【问题讨论】:

  • 有人知道为什么吗?是因为viewState问题还是我的逻辑问题?
  • 您是否将[Serializable] 属性添加到DistributionStandardPackingUnitItems 类?
  • @afzalulh 它有效。但是为什么要在类前面加上[Serializable]呢?
  • 在 ViewState 中保存 List 时,需要对它们进行序列化。见Why Viewstate can contain only serializable object?。我想知道为什么你没有收到任何错误!我之前有一个经验,当我忘记将我的类标记为可序列化时,列表中只保存了一个元素!
  • 我相信您的问题值得一票!由于场景复杂,这个问题没有得到足够的重视。

标签: c# asp.net gridview textbox


【解决方案1】:

请启用 tbQuantity 文本框 EnableAutoPostBack = True

【讨论】: