简体   繁体   English

在ASP.Net C#Webform中的HTML表中显示DataTable

[英]Display DataTable in HTML Table in ASP.Net C# Webform

I refer this website to try to write code - Display DataTable in HTML Table in ASP.Net C# Webform: http://www.aspsnippets.com/Articles/Display-DataTable-in-HTML-Table-in-ASPNet-using-C-and-VBNet.aspx 我指该网站尝试编写代码-在ASP.Net C#Webform的HTML表中显示数据表: http : //www.aspsnippets.com/Articles/Display-DataTable-in-HTML-Table-in-ASPNet-using- C和VBNet.aspx

But can't show table information,show empty page. 但无法显示表格信息,显示空白页。 How can I fix this code?Thanks. 我该如何解决此代码?谢谢。

1.CS.aspx 1.CS.aspx

 <%@ Page Language="C#" AutoEventWireup="true" CodeFile="CS.aspx.cs" Inherits="CS" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <style type="text/css">
`body { font-family: Arial;font-size: 10pt; }`

        table {
            border: 1px solid #ccc;
            border-collapse: collapse;
        }

            table th {
                background-color: #F7F7F7;
                color: #333;
                font-weight: bold;
            }

            table th, table td {
                padding: 5px;
                border-color: #ccc;
            }
    </style>
</head>
<body>
    <form id="form1" runat="server">
        <div style="margin-left: auto; margin-right: auto; text-align: center;">

            <asp:PlaceHolder ID="placeholder" runat="server" />

        </div>
    </form>
</body>
</html>

2.CS.aspx.cs 2.CS.aspx.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Data;
using System.Text;
using System.Configuration;




public partial class CS : System.Web.UI.Page
{

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!this.IsPostBack)
        {
            PlaceHolder placeholder = new PlaceHolder();

            //Populating a DataTable from database.
            DataTable dt = this.GetData();

            //Building an HTML string.
            StringBuilder html = new StringBuilder();

            //Table start.
            html.Append("<table border = '1'>");

            //Building the Header row.
            html.Append("<tr>");
            foreach (DataColumn column in dt.Columns)
            {
                html.Append("<th>");
                html.Append(column.ColumnName);
                html.Append("</th>");
            }
            html.Append("</tr>");

            //Building the Data rows.
            foreach (DataRow row in dt.Rows)
            {
                html.Append("<tr>");
                foreach (DataColumn column in dt.Columns)
                {
                    html.Append("<td>");
                    html.Append(row[column.ColumnName]);
                    html.Append("</td>");
                }
                html.Append("</tr>");
            }

            //Table end.
            html.Append("</table>");
            string strText = html.ToString();

            ////Append the HTML string to Placeholder.
            placeholder.Controls.Add(new Literal { Text = html.ToString() });

        }
    }

    private DataTable GetData()
    {
        string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
        using (SqlConnection con = new SqlConnection(constr))
        {
            using (SqlCommand cmd = new SqlCommand("SELECT TOP 10 [a01],[a02],[a03] FROM [aaa].[dbo].[bbb]"))
            {
                using (SqlDataAdapter sda = new SqlDataAdapter())
                {
                    cmd.Connection = con;
                    sda.SelectCommand = cmd;
                    using (DataTable dt = new DataTable())
                    {
                        sda.Fill(dt);
                        return dt;
                    }
                }
            }
        }
    }
}

Comment out this line and it will work: 注释掉这一行,它将起作用:

PlaceHolder placeholder = new PlaceHolder();

Just a thought.Rather than manually looping through the DataTable why not use the GridView control? 只是一个想法。为什么不使用GridView控件而不是手动遍历DataTable

Code behind: 后面的代码:

protected void Page_Load(object sender, EventArgs e)
{
    if (!this.IsPostBack)
    {
        DataTable dt = this.GetData();
        gridView.DataSource = dt;
        gridView.DataBind();
    }
}

ASPX Page: ASPX页面:

<asp:GridView ID="gridView" runat="server"></asp:GridView>

If I had the points, I would have just made a comment but to fix your problem, all you need to do is comment out the following line: 如果我有要点,我会发表评论,但要解决您的问题,您要做的就是注释掉以下行:

PlaceHolder placeholder = new PlaceHolder();

The reason being is that, you have a PlaceHolder named placeholder on your markup, then create a completely new placeholder variable of Type PlaceHolder in the load code. 原因是,您的标记上有一个名为placeholderPlaceHolder ,然后在装入代码中创建一个类型为PlaceHolder全新placeholder变量。 Whilst they are named the same, the code considers them 2 completely different objects. 虽然它们的名称相同,但是代码将它们视为2个完全不同的对象。 See code below, also I borrowed someone else's code to create a datatable , since I don't have access to your db. 请参见下面的代码, 还我借别人的代码来创建一个datatable ,因为我没有访问您的分贝。

protected void Page_Load(object sender, EventArgs e)
{
    if (!IsPostBack)
    {
        /*
        Commented out because doing it this way creates 
        2 PlaceHolder variables named placeholder, everything else is as needed
        */
        //PlaceHolder placeholder = new PlaceHolder();

        //Populating a DataTable from database.
        DataTable dt = this.GetData();
        //Building an HTML string.
        StringBuilder html = new StringBuilder();
        //Table start.
        html.Append("<table border = '1'>");
        //Building the Header row.
        html.Append("<tr>");
        foreach (DataColumn column in dt.Columns)
        {
            html.Append("<th>");
            html.Append(column.ColumnName);
            html.Append("</th>");
        }
        html.Append("</tr>");
        //Building the Data rows.
        foreach (DataRow row in dt.Rows)
        {
            html.Append("<tr>");
            foreach (DataColumn column in dt.Columns)
            {
                html.Append("<td>");
                html.Append(row[column.ColumnName]);
                html.Append("</td>");
            }
            html.Append("</tr>");
        }
        //Table end.
        html.Append("</table>");
        string strText = html.ToString();
        ////Append the HTML string to Placeholder.
        placeholder.Controls.Add(new Literal { Text = html.ToString() });
    }
}
private DataTable GetData()
{
    // Modified your method, since I don't have access to your db, so I created one manually
    // Here we create a DataTable with four columns.
    DataTable table = new DataTable();
    table.Columns.Add("Dosage", typeof(int));
    table.Columns.Add("Drug", typeof(string));
    table.Columns.Add("Patient", typeof(string));
    table.Columns.Add("Date", typeof(DateTime));

    // Here we add five DataRows.
    table.Rows.Add(25, "Indocin", "David", DateTime.Now);
    table.Rows.Add(50, "Enebrel", "Sam", DateTime.Now);
    table.Rows.Add(10, "Hydralazine", "Christoff", DateTime.Now);
    table.Rows.Add(21, "Combivent", "Janet", DateTime.Now);
    table.Rows.Add(100, "Dilantin", "Melanie", DateTime.Now);
    return table;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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