繁体   English   中英

在ASP.NET WebForm中从C#后端创建ASP:Table

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM