【问题标题】:Why I can't display data from database in HTML table in ASPNet.aspx为什么我不能在 ASPNet.aspx 的 HTML 表中显示数据库中的数据
【发布时间】:2015-05-22 08:06:23
【问题描述】:

我正在尝试将一些数据从 SQLserver 显示到 ASPNet 中的 HTML 表中,这是我目前的代码:

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;
using System.Data;


namespace WebApplication17
{
    public partial class WebForm1 : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
       {
        if (!this.IsPostBack)
        {
            //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>");

            //Append the HTML string to Placeholder.
            PlaceHolder1.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 id, Nome, Cognome FROM Anagrafica"))
            {
                using (SqlDataAdapter sda = new SqlDataAdapter())
                {
                    cmd.Connection = con;
                    sda.SelectCommand = cmd;
                    using (DataTable dt = new DataTable())
                    {
                        sda.Fill(dt);
                        return dt;
                    }
                }
               }
            }
        }
   }
}

到目前为止,这是我的 HTML 标记:

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="WebApplication17.WebForm1" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
     <title></title>
</head>
<body>
        <asp:PlaceHolder ID = "PlaceHolder1" runat="server" />
</body>
</html>

问题是:我在 constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString; 上不断收到 NullReferenceException 错误;

我无法修复它...请问有什么想法吗?感谢您的建议。

【问题讨论】:

  • 确保您在 Web.Config 文件中定义了constr。另外,请检查此stackoverflow.com/questions/4660142/… 以了解错误。
  • @RahulSingh 你能给我一些代码来声明它吗?我对此很陌生。

标签: c# html asp.net sql-server


【解决方案1】:

好的,我找到了一个可行的解决方案:

private DataTable GetData()
    {

        SqlConnection con = new SqlConnection("Data Source=NB465\\SQLEXPRESS;Initial Catalog=Movie;Integrated Security=True");
        con.Open();
        SqlCommand cmd = new SqlCommand("SELECT id, Nome, Cognome FROM Anagrafica");
        SqlDataAdapter sda = new SqlDataAdapter(cmd);
        cmd.Connection = con;
        sda.SelectCommand = cmd;
        DataTable dt = new DataTable();
        sda.Fill(dt);
        return dt;
    }

【讨论】:

【解决方案2】:

您需要在configuration 节点中的 Web.Config 文件中添加类似这样的连接字符串:-

Working with Configuration file & Connection Strings

<configuration>
    <connectionStrings>
      <add name="constr" 
       providerName="System.Data.SqlClient" 
       connectionString="Data Source=.\SQLEXPRESS;AttachDbFilename=
             |DataDirectory|\Database1.mdf;Integrated Security=True;" />
    </connectionStrings>
  </configuration>

这些是基础知识,您应该参考 MSDN 的一些教程。

【讨论】:

  • 谢谢!有效!但现在由于某些其他原因,我收到此错误:System.Data.dll 中发生了“System.InvalidOperationException”类型的异常,但未在 sda.Fill(dt) 上的用户代码中处理;
  • @FabioEnne - 不要像这样使用 using 创建 DataTable - using (DataTable dt = new DataTable()),像这样创建它作为普通实例: - DataTable dt = new DataTable(); sda.Fill(dt);
  • @RahulSingh 完成了,但在 sda.Fill(dt) 上继续出现同样的错误;
  • @FabioEnne - 我不确定出了什么问题。请搜索这个错误,当连接未打开或连接已经打开时发生。
猜你喜欢
  • 2014-11-19
  • 1970-01-01
  • 2021-01-31
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-08-24
  • 2018-09-14
相关资源
最近更新 更多