【发布时间】: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