Mahmoud Ashraf
Mahmoud Ashraf

Reputation: 67

Bug in adding rows to table on the fly

i try adding rows to table on the fly from DataBase but its always the last row that appears only where am i wrong ?


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

it should show all the data rows in able

Upvotes: 1

Views: 56

Answers (1)

ADyson
ADyson

Reputation: 61859

Your table cells are not unique to each iteration of the loop. When you add a cell variable to a row, it maintains a reference to that variable, not a copy. So then in the next iteration of the loop you overwrite the cell variable with the value from the new row, this will also update all the references to that cell.

To fix it, simply move the table cell declarations inside the loop, then their scope will be limited to that iteration, and new variables will be created each time you loop - just like the table row variable already is, in fact:

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

Upvotes: 1

Related Questions