簡體   English   中英

動態將行添加到HTML表

[英]Adding rows dynamically to a HTML table

我有一個包含一些表的asp.net網站。 但是這些不是asp:Table,即它們是以這種方式構建的簡單HTML表:

 <table><tr><td></td></tr></table> 

現在,我想知道是否可以從后面的代碼(即C#)向該表動態添加行,如果可以,我該如何去做?

您可以給它一個Id並設置runat =“ server”屬性,並使用您給它的Id從后面的代碼中使用它

System.Web.UI.HtmlControls.HtmlTableRow r=new System.Web.UI.HtmlControls.HtmlTableRow();
            System.Web.UI.HtmlControls.HtmlTableCell c = new System.Web.UI.HtmlControls.HtmlTableCell();
            c.InnerText = "New Cell";
            r.Cells.Add(c);
            T.Rows.Add(r);

其中T是表的ID

已經有一段時間了,但是ASP.NET Webforms中有用於此類內容的中繼器控件。

這是一篇介紹這一概念的不錯的文章: ASP.NET中的數據轉發器控件

我認為這比使用AJAX / JScript進行黑客攻擊更容易

除此之外:Daniel Casserly是正確的-如果您在MVC中進行操作,這非常容易(如果使用Razor-Syntax,則更加容易),因為它將轉換為類似以下內容:

<table>
    @foreach (var item in Model)
    {
        <tr>
            <td>@item.Name</td>
            ... whatever you need here ...
        </tr>
    }
</table>

您可以使用JQuery進行此操作,但為此您需要提供ID和ID或類,或者僅搜索表數組,然后向其中注入行

我認為最好從后面的代碼創建整個HTML表。 為此,我們可以添加一個文字,並在后面的代碼中使用它,以便從后面的代碼中添加表結構。

例如,讓我們制作一個HTML表格的Birds詳細信息。 為了使說明簡短,我沒有包括充滿鳥類細節的數據表部分。

if (dtBirdsDetail.Rows.Count > 0)
    {
      litBirdsTable.Text = "<center><table id='tbldata' cellspacing='0' cellpadding='1' border='1' style='border-collapse: collapse;'>" + System.Environment.NewLine;
      litBirdsTable.Text += "<tr>";

      //add datatable columns to html table as heading
for (int liColumnIndex = 0; liColumnIndex < dtBirdsDetail.Columns.Count;liColumnIndex++)
       {
         litBirdsTable.Text += "<th>" + dtBirdsDetail.Columns[liColumnIndex].ColumnName 
                             + "</th>" +   System.Environment.NewLine;
       }
       litBirdsTable.Text += System.Environment.NewLine + "</tr>";

       //add datatable rows to html table
       for (int liRowIndex = 0; liRowIndex < dtBirdsDetail.Rows.Count; liRowIndex++)
       {
         litBirdsTable.Text += "<tr>";
         litBirdsTable.Text += "<td>" + dtBirdsDetail.Rows[liRowIndex]["ID"] + "</td>" +              
                                System.Environment.NewLine;
         litBirdsTable.Text += "<td>" + dtBirdsDetail.Rows[liRowIndex]["BirdName"] + " 
                               </td>" + System.Environment.NewLine;
         litBirdsTable.Text += "<td>" + dtBirdsDetail.Rows[liRowIndex]["TypeOfBird"] + " 
                               </td>" + System.Environment.NewLine;
         litBirdsTable.Text += "<td>" + dtBirdsDetail.Rows[liRowIndex]["ScientificName"] 
                             + "</td>" + System.Environment.NewLine;
         litBirdsTable.Text += "</tr>";
       }
        litBirdsTable.Text += "</table></center>";
    }

有關詳細說明,請訪問此鏈接:

http://codevariation.blogspot.com/2018/03/html-table-design-with-dynamic-data.html

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM