在行中向表中添加行的错误

时间:2019-04-24 13:29:03

标签: c# asp.net

我尝试从数据库动态地向表中添加行,但它总是最后一行仅出现在我错的地方?


            TableCell pNameCell = new TableCell();
            TableCell pDescCell = new TableCell();
            TableCell pPriceCell = new TableCell();
            TableCell pStockCell = new TableCell();
            TableCell buyProduct = new TableCell();
            HyperLink hl = new HyperLink();

//ds is DataSet
            foreach (DataRow dRow in ds.Tables[0].Rows)
            {
                TableRow row = new TableRow();
                pNameCell.Text = dRow["name"].ToString();
                row.Cells.Add(pNameCell);
                pDescCell.Text = dRow["description"].ToString();
                row.Cells.Add(pDescCell);
                pPriceCell.Text = dRow["price"].ToString();
                row.Cells.Add(pPriceCell);
                pStockCell.Text = dRow["Qty"].ToString();
                row.Cells.Add(pStockCell);
                hl.Text = "Add To Cart";
                hl.NavigateUrl = "BuyProduct.aspx?id="+ dRow["pro_id"].ToString();
                hl.CssClass = "btn btn-primary";
                buyProduct.Controls.Add(hl);
                row.Cells.Add(buyProduct);
//TProducts is asp:table ID
                TProducts.Rows.Add(row);
            }

它应该显示所有数据行

1 个答案:

答案 0 :(得分:1)

您的表单元格对于循环的每次迭代不是唯一的。当您将单元格变量添加到行中时,它会维护对该变量的引用,而不是副本。因此,在循环的下一次迭代中,您用新行中的值覆盖单元格变量,这还将更新对该单元格的所有引用。

要解决此问题,只需在循环内移动表单元格声明,然后将它们的范围限制为该迭代,并且每次循环时都会创建新变量-实际上就像表行变量一样:

//ds is DataSet
foreach (DataRow dRow in ds.Tables[0].Rows)
{
  TableCell pNameCell = new TableCell();
  TableCell pDescCell = new TableCell();
  TableCell pPriceCell = new TableCell();
  TableCell pStockCell = new TableCell();
  TableCell buyProduct = new TableCell();
  HyperLink hl = new HyperLink();
  TableRow row = new TableRow();

  pNameCell.Text = dRow["name"].ToString();
  row.Cells.Add(pNameCell);
  pDescCell.Text = dRow["description"].ToString();
  row.Cells.Add(pDescCell);
  pPriceCell.Text = dRow["price"].ToString();
  row.Cells.Add(pPriceCell);
  pStockCell.Text = dRow["Qty"].ToString();
  row.Cells.Add(pStockCell);
  hl.Text = "Add To Cart";
  hl.NavigateUrl = "BuyProduct.aspx?id="+ dRow["pro_id"].ToString();
  hl.CssClass = "btn btn-primary";
  buyProduct.Controls.Add(hl);
  row.Cells.Add(buyProduct);
  //TProducts is table ID
  TProducts.Rows.Add(row);
}