Skip to main content
 首页 » 编程设计

c#之从后面的代码向现有的 html 表添加行

2024年02月20日14lori

更多新手:)

我使用下面的 html 代码创建了 HTML 表格

 <table runat="server" id="Table1" border="1" class="style1"> 
    <tr> 
        <td class="style2" colspan="3"> 
            Info.</td> 
        <td class="style2" colspan="2"> 
            TypeA</td> 
        <td class="style2"> 
            TypeB</td> 
        <td class="style2" rowspan="2"> 
            TypeC</td> 
    </tr> 
    <tr> 
        <td class="style3"> 
            Dept.</td> 
        <td class="style3"> 
            Div.</td> 
        <td class="style3"> 
            Unit</td> 
        <td class="style3"> 
            TypeA.1</td> 
        <td class="style3"> 
            TypeA.1</td> 
        <td style="text-align: center"> 
            TypeB.1</td> 
    </tr> 
</table> 

我尝试使用

为其添加行
protected void Button1_Click(object sender, EventArgs e) 
{ 
    TableRow tRow = new TableRow(); 
    for (int i = 1; i < 8; i++) 
    { 
        TableCell tb = new TableCell(); 
        tb.Text = "text"; 
        tRow.Controls.Add(tb); 
    } 
    Table1.Rows.Add(tRow); 
} 

但是我得到了:

The best overloaded method match for 'System.Web.UI.HtmlControls.HtmlTableRowCollection.Add(System.Web.UI.HtmlControls.HtmlTableRow)' has some invalid arguments

我用谷歌搜索,但一无所获。

我这样做是为了避免代码隐藏中的列标题合并操作,同时我仍然需要寻找如何合并行标题。这是完成 https://stackoverflow.com/questions/13670384/asp-net-dynamic-input-display-table-by-section-with-multi-columns-rows-headers 的最后一步

,.. 更近的标题 View 是:

创建的行将有一个转发标题单元格,如果它与上面的行相同则应该合并。感谢 StackOverflow 成员(member)的好 helper 。

请您参考如下方法:

错误在异常中很明显。

您正在使用 TableRow 而不是 HtmlTableRow。
将鼠标悬停在 TableRow tRow = new TableRow(); 上以查看 TableRow 类来自哪个命名空间。

需要对单元格进行类似的更改。即使用 HtmlTableCell 而不是 TableCell。

编辑:Table、TableRow 是来自 System.Web.UI.WebControls 命名空间的类。
而 HtmlTable、HtmlTableRow 是来自 System.Web.UI.HtmlControls 命名空间的类。