繁体   English   中英

动态地向表中添加行

[英]Add rows to a table dynamically

目前我正在尝试创建一个表,其内容应该由子类创建(查询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> 

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

它正在工作,我测试过它:

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

 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>

我会使用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或类似的东西

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

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

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

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

        }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM