[英]Creating asp:Table from c# backend in asp.net webform
由於某種原因,我的代碼沒有像普通表那樣顯示,而是輸出一個文本塊。
這是我在后端編寫的用於創建表的代碼:
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 SPuge3 SPugeRSleyL PMWSPeuget PTVoltPetrot GT3Peugeot 1.9 。 5 / 16BLSFord CVH 1600F3 5 / 16F3 5/16福特Zetec襯套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 SP6 4.926 WideHonda 5L。奧迪5缸標致SPF3未知V6山地特別勝利SPVauxhall Corsa Ext。福特考斯沃斯SierraF3福特窄版SPRS2000 SP考斯沃斯
我只希望它以表結構形式出現
這是給你的一個好例子:( 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字符串並為您分配文字,僅此而已!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.