如何将 DataTable 从类传递到页面
我正在学习 C# 中的类,并尝试构建一个“DataAccessClass”。我有一个正在工作的“OpenSqlConnection”空白,并使用它作为构建“OpenSqlDatareader”空白的指南。我正在尝试合并此类中的所有数据库调用。我困惑的是如何将 DataTable 从类传递到 aspx 页面以将其与 ListView 绑定。我已经阅读并尝试了一天来完成这项工作,但无法弄清楚我做错了什么...
这是 Page_Load:
// --------------------------------------------------------------------------------
// Populate the Customers page.
// --------------------------------------------------------------------------------
// Define the query
string sqlQuery = " SELECT CustomerID, LastName + ', ' + FirstName AS CustomerName, Email, City, State, Phone"
+ " FROM Customer"
+ " ORDER BY LastName, FirstName";
string strErrorMessage = "";
if (DataAccessClass.OpenSqlConnection(out strErrorMessage) == false)
{
string strErrorType = "Database Connection Error:";
SendErrorMessageToClient(strErrorType, strErrorMessage);
}
else if (DataAccessClass.OpenSqlDatareader(sqlQuery, out dt, out strErrorMessage) == false)
{
string strErrorType = "Datareader Error:";
SendErrorMessageToClient(strErrorType, strErrorMessage);
}
else
{
// Bind the Listview
lvCustomers.DataSource = dt;
lvCustomers.DataBind();
dt.Dispose();
}
这是类:
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.Configuration;
using System.Data;
/// <summary>
/// Summary description for DataAccessClass
/// </summary>
///
public class DataAccessClass
{
public DataAccessClass()
{
//
// TODO: Add constructor logic here
//
}
// -----------------------------------------------------------------------------------------
// Name: OpenSqlConnection
// Abstract: Open a connection to a SQL Server
// -----------------------------------------------------------------------------------------
public static bool OpenSqlConnection(out string strErrorMessage)
{
SqlConnection theConnection = new SqlConnection();
bool blnResult = false;
string strConnectionString = ConfigurationManager.ConnectionStrings["MyConn"].ConnectionString;
strErrorMessage = "";
if (theConnection == null)
theConnection = new SqlConnection();
try
{
switch (theConnection.State)
{
case ConnectionState.Broken:
theConnection.Close();
theConnection.ConnectionString = strConnectionString;
theConnection.Open();
blnResult = true;
break;
case ConnectionState.Closed:
theConnection.ConnectionString = strConnectionString;
theConnection.Open();
blnResult = true;
break;
case ConnectionState.Open:
blnResult = true;
break;
default:
strErrorMessage = "Connection state is " + theConnection.State.ToString();
break;
}
}
catch (Exception excError)
{
strErrorMessage = excError.Message;
}
return blnResult;
}
// -----------------------------------------------------------------------------------------
// Name: OpenSqlDataReader
// Abstract: Open a SQL DataReader
// -----------------------------------------------------------------------------------------
public static bool OpenSqlDatareader(string sqlQuery, out dt, out string strErrorMessage)
{
SqlConnection theConnection = new SqlConnection();
bool blnResult = false;
string strConnectionString = ConfigurationManager.ConnectionStrings["MyConn"].ConnectionString;
strErrorMessage = "";
if (theConnection == null)
theConnection = new SqlConnection();
try
{
// Declare a SQL Adapter
SqlDataAdapter da = new SqlDataAdapter(sqlQuery, theConnection);
// Declare a DataTable
DataTable dt = new DataTable();
// Populate the DataTable
da.Fill(dt);
// Clean up.
dt.Dispose();
da.Dispose();
theConnection.Close();
}
catch (Exception excError)
{
strErrorMessage = excError.Message;
}
return blnResult;
}
}
错误消息是:“类型或命名空间名称 'dt' 无法被发现(您是否缺少 using 指令或程序集引用?)” 有什么建议吗?
I'm learning about classes in C# and am trying to build a "DataAccessClass". I have a working "OpenSqlConnection" void and am using it as a guide to build a "OpenSqlDatareader" void. I am attempting to consolidate all my database calls in this class. My boggle is how to pass a DataTable from the class to the aspx page to bind it with a ListView. I have been reading and trying for a day to make this work and cannot figure out what I am doing wrong...
Here's the Page_Load:
// --------------------------------------------------------------------------------
// Populate the Customers page.
// --------------------------------------------------------------------------------
// Define the query
string sqlQuery = " SELECT CustomerID, LastName + ', ' + FirstName AS CustomerName, Email, City, State, Phone"
+ " FROM Customer"
+ " ORDER BY LastName, FirstName";
string strErrorMessage = "";
if (DataAccessClass.OpenSqlConnection(out strErrorMessage) == false)
{
string strErrorType = "Database Connection Error:";
SendErrorMessageToClient(strErrorType, strErrorMessage);
}
else if (DataAccessClass.OpenSqlDatareader(sqlQuery, out dt, out strErrorMessage) == false)
{
string strErrorType = "Datareader Error:";
SendErrorMessageToClient(strErrorType, strErrorMessage);
}
else
{
// Bind the Listview
lvCustomers.DataSource = dt;
lvCustomers.DataBind();
dt.Dispose();
}
And here's the class:
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.Configuration;
using System.Data;
/// <summary>
/// Summary description for DataAccessClass
/// </summary>
///
public class DataAccessClass
{
public DataAccessClass()
{
//
// TODO: Add constructor logic here
//
}
// -----------------------------------------------------------------------------------------
// Name: OpenSqlConnection
// Abstract: Open a connection to a SQL Server
// -----------------------------------------------------------------------------------------
public static bool OpenSqlConnection(out string strErrorMessage)
{
SqlConnection theConnection = new SqlConnection();
bool blnResult = false;
string strConnectionString = ConfigurationManager.ConnectionStrings["MyConn"].ConnectionString;
strErrorMessage = "";
if (theConnection == null)
theConnection = new SqlConnection();
try
{
switch (theConnection.State)
{
case ConnectionState.Broken:
theConnection.Close();
theConnection.ConnectionString = strConnectionString;
theConnection.Open();
blnResult = true;
break;
case ConnectionState.Closed:
theConnection.ConnectionString = strConnectionString;
theConnection.Open();
blnResult = true;
break;
case ConnectionState.Open:
blnResult = true;
break;
default:
strErrorMessage = "Connection state is " + theConnection.State.ToString();
break;
}
}
catch (Exception excError)
{
strErrorMessage = excError.Message;
}
return blnResult;
}
// -----------------------------------------------------------------------------------------
// Name: OpenSqlDataReader
// Abstract: Open a SQL DataReader
// -----------------------------------------------------------------------------------------
public static bool OpenSqlDatareader(string sqlQuery, out dt, out string strErrorMessage)
{
SqlConnection theConnection = new SqlConnection();
bool blnResult = false;
string strConnectionString = ConfigurationManager.ConnectionStrings["MyConn"].ConnectionString;
strErrorMessage = "";
if (theConnection == null)
theConnection = new SqlConnection();
try
{
// Declare a SQL Adapter
SqlDataAdapter da = new SqlDataAdapter(sqlQuery, theConnection);
// Declare a DataTable
DataTable dt = new DataTable();
// Populate the DataTable
da.Fill(dt);
// Clean up.
dt.Dispose();
da.Dispose();
theConnection.Close();
}
catch (Exception excError)
{
strErrorMessage = excError.Message;
}
return blnResult;
}
}
The error message is: "The type or namespace name 'dt' could not be found (are you missing a using directive or an assembly reference?)"
Any suggestions?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
要添加到此代码的问题列表(您尚未发现,因为您还没有做到这一点):
在您的
OpenSqlDataReader
方法中,您需要实例化您的SqlConnection< /code> 使用您定义的连接字符串的对象。现在您只是使用空构造函数创建它,这意味着它不会充当实际的连接对象。
此外,您还需要在连接对象上显式调用 .
Open()
。否则,它将不会打开,并且当您尝试使用它时会抛出异常。To add to the list of problems with this code (which you haven't discovered yet because you haven't gotten that far):
In your
OpenSqlDataReader
method, you need to instantiate yourSqlConnection
object using the connection string you've defined. Right now you're just creating it with the empty constructor, which means it will not function as an actual connection object.Also, you'll need to explicitly call .
Open()
on your connection object. Otherwise, it won't be open and you'll get an exception thrown when you attempt to use it.在调用 OpenSqlDatareader 之前,您需要声明
dt
使用
out DataTable dt
更改 OpenSqlDatareader 的签名在方法内
before calling OpenSqlDatareader you need to declare
dt
change your signature of OpenSqlDatareader with
out DataTable dt
inside the method
在
Page_Load
中,您还需要声明dt
。In
Page_Load
you'll also need to declaredt
.