由于某些原因,我的代码没有像普通表那样显示,而是只输出一个文本块。
以下是我在后端编写的用于创建表格的代码:
protected void LoadData(object sender, ImageClickEventArgs e)
{
//Populating a DataTable from database.
DataTable dt = this.GetData();
//Building an HTML string.
StringBuilder html = new StringBuilder();
//Table start.
html.Append("<asp:Table ID=\"Table2\" runat=\"Server\" CellPadding=\"2\" CellSpacing=\"1\" BorderColor = \"CadetBlue\" BorderWidth = \"1\" BorderStyle = \"Dashed\" >");
//Building the Data rows.
foreach (DataRow row in dt.Rows)
{
html.Append("<asp:TableRow runat=\"Server\" BorderWidth=\"1\">");
foreach (DataColumn column in dt.Columns)
{
html.Append("<asp:TableCell runat=\"Server\" BorderWidth=\"1\">");
html.Append(row[column.ColumnName]);
html.Append("</asp:TableCell>");
}
html.Append("</asp:TableRow>");
}
//Table end.
html.Append("</asp:Table>");
//Append the HTML string to Placeholder.
PlaceHolder1.Controls.Add(new Literal { Text = html.ToString() });
}
这是输出的示例:
Yamaha XTZ 650)N / Yamaha TRXBentley H-SectionBentley I-SectionBMW SPFord 5.23 NarrowFord 6.173 NarrowSuzuki GSX-R 750Non-Split I-SectionNissan GTR6Peugeot 1.9Vauxhall CorsaFerrariBMW SPFord SPTR3 SPTR6 SPSteyr PuchClimax WLKHealey 3000Vauxhall SPRS2000Peugeot / BMWPeugeot 5 / 16MGB 1800Peugeot 3 / 8F3分机5 / 16BLSFord CVH 1600F3 5 / 16F3 5 / 16Ford Zetec Bushed S / EFord 5.65 NarrowPeugeot SPFord Zetec SPVolvo SPVolvo SPBMW SPPeugeotFord 5.4 SPOpel 2.3 DAlfa Romeo V6LagondaVauxhall Ext.Ford 5.4 NarrowFord 5.0 NarrowFord 4.926 WideHonda CRXPeugeot 5/16 SPMini Cooper Ext.Lagonda Ext。奥迪5CylPeugeot SPF3Unknown V6Mountune SpecialTriumph SPVauxhall Corsa Ext.Ford考斯沃斯SierraF3Ford窄型SPRS2000 SPCosworth
我只是希望它以表结构出现'
答案 0 :(得分:0)
以下是一个很好的例子:(https://forums.asp.net/t/1797172.aspx?How+to+create+table+dynamically+in+asp+net)
首先在您要显示表格的页面中放置一个asp:Literal控件,如下所示
<asp:Literal ID="litTable" runat="server" />
现在,在您获取数据的事件中,编写以下代码以循环访问数据源并构建表
StringBuilder htmlTable = new StringBuilder();
htmlTable .AppendLine("<table">");
htmlTableString.AppendLine("<tr>");
htmlTableString.AppendLine("<th>colum 1</th>");
htmlTableString.AppendLine("<th>colum 2</th>");
htmlTableString.AppendLine("<th>colum 3</th>");
htmlTableString.AppendLine("</tr>");
/ 在此处输入一个for循环并重复以下代码 /
htmlTableString.AppendLine("<tr>");
htmlTableString.AppendLine("<td>colum 1 data</td>");
htmlTableString.AppendLine("<td>colum 2 data</td>");
htmlTableString.AppendLine("<td>colum 3 data</td>");
htmlTableString.AppendLine("</tr>");
/ 结束循环 /
htmlTableString.AppendLine("</table>");
litTable.Text = htmlTableString.ToString();
这将创建一个HTML字符串,并为您分配文字,即全部!