簡體   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