动态向表添加行的错误



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


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

它应该在 ABLE 中显示所有数据行

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

要修复它,只需将表单元格声明移动到循环内,然后它们的作用域将仅限于该迭代,并且每次循环时都会创建新变量 - 就像表行变量一样,实际上:

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

最新更新