动态地向表中添加行

时间:2012-06-02 11:18:23

标签: asp.net html-table

目前我正在尝试创建一个表,其内容应该由子类创建(查询RESTful Web服务的结果)。我现在已经工作了很长一段时间,我似乎无法让它发挥作用。我尝试了很多不同的解决方案。

  • 在子类中创建表并将其添加到Page.Controls。这让我“无法修改控件集合,因为控件包含代码块(即<%...%>)。”这根本没有意义。
  • 我试图在页面上创建一个空表,并将其句柄传递给负责添加行的子类。注意到了。
  • 我试图返回一个TableRowCollection并将其分配给之前创建的(空)表。什么都没发生。
  • 现在我只想在桌子上添加一行和一个单元格(宝贝迈向我需要的东西)。甚至不行。请找到附件的代码:

    TableRow row = new TableRow();
    table.Rows.Add(row);
    
    TableCell cell = new TableCell();
    row.Cells.Add(cell);
    
    cell.Controls.Add(new TextBox());
    

表格简单而空白:

<asp:Table ID="table" runat="server" /> 

我的浏览器显示的源代码如下:

<table id="table">
</table> 

我一直在网上看过无数的例子,看起来都像这样。我想这在某个地方只是一个小问题,但我无法弄明白。现在,我愿意向所有能够提供解决这一混乱的人提供终生的感激之情。

4 个答案:

答案 0 :(得分:4)

它正在运行,我已对其进行了测试:

在我的页面加载中,我有:

 protected void Page_Load(object sender, EventArgs e)
        {
            TableRow row = new TableRow();
            TableCell cell = new TableCell();
            cell.Controls.Add(new TextBox());
            row.Cells.Add(cell);
            table.Rows.Add(row);
        }

在我的aspx页面上,我有:

<asp:Content ID="BodyContent" runat="server" ContentPlaceHolderID="MainContent">
    <asp:Table ID="table" runat="server" /> 
</asp:Content>

此代码呈现的html:

<table id="MainContent_table">
    <tbody><tr>
        <td><input name="ctl00$MainContent$ctl00" type="text"></td>
    </tr>
</tbody></table>

答案 1 :(得分:1)

我会使用asp:GridView或asp:Repeater

例如使用Repeater

    <table>
        <asp:Repeater id="repeater1" runat="server">
            <ItemTemplate>
                <tr>
                    <td><asp:Literal id="literal1" runat="server" /></td>
                </tr>
            </ItemTemplate>
        </asp:Repeater>
    </table>

然后在你的代码中

repeater1.DataSource = myDatasource;
repeater1.DataBind();

或者您可以使用GridView

使用table.Rows.Add()会导致问题,特别是在回发时内容消失,或者事件处理程序无法触发的问题,如果您需要向表格单元格添加任何LinkBut​​tons或类似的东西

答案 2 :(得分:0)

问题是你在表格中添加这些行的位置,我的意思是页面的哪个事件?

因为我觉得回发后正在清除所有添加的行。

请告诉执行顺序,并尝试将您的代码放在page_init事件中以添加行。

答案 3 :(得分:0)

Might solve your problem.
Make table runat="server" in your aspx code
<table id="tbl" runat="server">
</table> 



    protected void Page_Load(object sender, EventArgs e)
        {
                  if(!IsPostBack)
              {
            TableRow tr = new TableRow();

            TableCell tc = new TableCell();
            TextBox txtBox = new TextBox();

            // Add the control to the TableCell
            tc.Controls.Add(txtBox);
            // Add the TableCell to the TableRow
            tr.Cells.Add(tc);

            // Add the TableRow to the Table
            tbl.Rows.Add(tr);
                  }

        }