4

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

  • 在子类中创建表并将其添加到 Page.Controls。这让我“无法修改 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

4 回答 4

5

它正在工作,我已经测试过了:

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

 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>
于 2012-06-02T11:36:04.630 回答
1

我会使用 asp:GridView 或 asp: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 或类似的东西添加到表格单元格中,事件处理程序不会触发的问题

于 2012-06-02T11:31:35.720 回答
0

问题是您在表中的何处添加这些行,我的意思是在哪个页面事件中?

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

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

于 2012-06-02T12:01:47.030 回答
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);
                  }

        }
于 2012-06-02T12:03:27.427 回答