动态添加Table到html
我现在有一段代码要动态生成一个table然后添加到html
HtmlTable table1 = new HtmlTable();
table1.Border = 1;
HtmlTableRow row;
HtmlTableCell cell;
for (int i = 0; i < dt.Rows.Count; i++) {
row = new HtmlTableRow();
cell = new HtmlTableCell();
cell.InnerHtml = dt.Rows[i][0].ToString();
row.Cells.Add(cell);
cell = new HtmlTableCell();
cell.InnerHtml = dt.Rows[i][1].ToString();
row.Cells.Add(cell);
cell = new HtmlTableCell();
cell.InnerHtml = dt.Rows[i][2].ToString();
row.Cells.Add(cell);
cell = new HtmlTableCell();
cell.InnerHtml = dt.Rows[i][3].ToString();
row.Cells.Add(cell);
cell = new HtmlTableCell();
cell.InnerHtml = dt.Rows[i][4].ToString();
row.Cells.Add(cell);
table1.Rows.Add(row);
}
Page.Controls.Add(table1);
<%@ page language="C#" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <html> <head> <script type="text/javascript"> function contactlist(){ var table = document.getElementById("contactTable"); var tr = table.insertRow(table.rows.length);//添加一行 tr.align="center"; tr.bgcolor="#F3F4F3"; tr.height="23"; //添加五列 var td0 = tr.insertCell(0); td0.width="20%"; var td1 = tr.insertCell(1); td1.width="20%"; var td2 = tr.insertCell(2); td2.width="8%"; var td3 = tr.insertCell(3); td3.width="30%"; var td4 = tr.insertCell(4); td4.width="20%"; //设置列内容 td0.innerHTML = ""; td1.innerHTML = "<input type='file' id='dataAudio' name='dataAudio'/><input type='hidden' name='dataAudios'/><input type='hidden' name='audioOldName'/>"; td2.innerHTML = "<input type='text' name='playDateTime' id='playDateTime' onkeyup='validateNumber(this);' size='5' maxlength='3' style='color: red' />"; td3.innerHTML = "<input type='text' name='content' id='content' size='35' maxlength='300'/>"; td4.innerHTML = "<input type='button' value='删除' onclick='removeRow(this.parentNode.parentNode)'/>"; } function removeRow(r) { var root = r.parentNode; var allRows = root.getElementsByTagName('tr'); if(allRows.length > 3){ root.removeChild(r); }else{ alert("不能删除改行!"); } } </script > </head> <body> <table id="contactTable" width="98%" border="0" align="center" cellpadding="0" cellspacing="1" bgcolor="#D9D9D9"> <tr bgcolor="#F3F4F3" align="center" height="23"> <td colspan="5" align="left"><input type="button" value="添加帧" class="button" onclick="return contactlist();"/></td> </tr> <tr bgcolor="#F3F4F3" align="center" height="23"> <td width="20%">上传图片</td> <td width="20%">上传声音</td> <td width="8%">播放时间</td> <td width="30%">内 容</td> <td width="20%">操作</td> </tr> </table> </body> </html>