如何将 DataTable 从类传递到页面

发布于 2024-12-14 06:59:34 字数 4363 浏览 3 评论 0原文

我正在学习 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

守不住的情 2024-12-21 06:59:34

要添加到此代码的问题列表(您尚未发现,因为您还没有做到这一点):

在您的 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 your SqlConnection 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.

殊姿 2024-12-21 06:59:34

在调用 OpenSqlDatareader 之前,您需要声明 dt

DataTable dt;// no need to assign 

....
else if (DataAccessClass.OpenSqlDatareader(sqlQuery, out dt, out strErrorMessage) == false)
{
    string strErrorType = "Datareader Error:";
    SendErrorMessageToClient(strErrorType, strErrorMessage);
}
...

使用 out DataTable dt 更改 OpenSqlDatareader 的签名

public static bool OpenSqlDatareader(string sqlQuery, out DataTable dt, out string strErrorMessage)

在方法内

// create new  DataTable
dt = new DataTable();

before calling OpenSqlDatareader you need to declare dt

DataTable dt;// no need to assign 

....
else if (DataAccessClass.OpenSqlDatareader(sqlQuery, out dt, out strErrorMessage) == false)
{
    string strErrorType = "Datareader Error:";
    SendErrorMessageToClient(strErrorType, strErrorMessage);
}
...

change your signature of OpenSqlDatareader with out DataTable dt

public static bool OpenSqlDatareader(string sqlQuery, out DataTable dt, out string strErrorMessage)

inside the method

// create new  DataTable
dt = new DataTable();
瀞厅☆埖开 2024-12-21 06:59:34

Page_Load 中,您还需要声明 dt

In Page_Load you'll also need to declare dt.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文