HtmlTableCellCollection.Add()每次都需要新的Cell实例?

时间:2014-12-02 13:03:46

标签: c# html asp.net

    ContentPlaceHolder wrapperCPH = (ContentPlaceHolder)this.Master.FindControl("ContentPlaceHolder1");
    HtmlTable tblCumulativeCredits = (HtmlTable)wrapperCPH.FindControl("tblCumulativeCredits");
    //If your table is not inside of a ContentPlaceHolder, you can just test with "this.FindControl("yourHTMLTableID");

    HtmlTableRow tableRow = new HtmlTableRow();
    HtmlTableCell tableCellAmount = new HtmlTableCell();
    HtmlTableCell tableCellCurrency = new HtmlTableCell();

    tableCellAmount.InnerText = item.amount.ToString();
    tableCellCurrency.InnerText = item.currencyCode.code;

    tableRow.Cells.Add(tableCellAmount);
    tableRow.Cells.Add(tableCellCurrency);
    tableRow.Cells.Add(tableCellCurrency);

    tblCumulativeCredits.Rows.Add(tableRow);

HTML:

<table id="tblCumulativeCredits" runat="server">
    <tr>
        <th class="th">Amount</th>
        <th class="th">Currency1</th>
        <th class="th">Currency2</th>           
    </tr>
</table>

现在假设我在循环中使用此代码示例添加行,并且在某些情况下我知道我的Currency1 = Currency2。所以我使用与上面例子相同的Cell对象。但是,如果我像示例一样添加相同的货币,那就有趣了;它只添加第一个,第三个单元格(Currency3)为空。 如果我创建 Cell实例,并添加它,它只会添加第二种货币:

    tableRow.Cells.Add(tableCellAmount);
    tableRow.Cells.Add(tableCellCurrency1);
    tableRow.Cells.Add(tableCellCurrency2);

我认为这是我第一次看到“Add()”方法正在以这种方式工作。不应该在引擎盖下创建给定参数(单元格对象)的新实例吗?如果有人能解释这背后的逻辑是什么,我会很感激吗?谢谢

1 个答案:

答案 0 :(得分:0)

我认为它与&#34;添加&#34;的实施无关。方法,相反我认为这发生在渲染过程中。 请记住,您正在添加相同的实例两次,这不仅意味着单元格的值(也许是某种类型的引用,以及#34;覆盖&#34;行为)。 所以,你最好创建一个新实例。

干杯