【问题标题】:Can I close a SqlDataReader after DataBind()我可以在 DataBind() 之后关闭 SqlDataReader
【发布时间】:2014-08-28 18:39:20
【问题描述】:

说我做这样的事情

using (SqlDataReader allUsersDataSource = AdminDB.GetUsers())
{
    // bind all portal users to dropdownlist
    allUsers.DataSource = allUsersDataSource;
    allUsers.DataBind();
}

dataBinded 是否仍会正常运行,还是需要取消处置 SqlDataReader

编辑:附加信息

public static SqlDataReader GetUsers() 
{
    // Create Instance of Connection and Command Object
    using (SqlConnection myConnection = new SqlConnection( (string) PortalSettings.GetPortalSetting("ConnectionString")))
    using (SqlCommand myCommand = new SqlCommand("dbo.GetUsers", myConnection))
    {

        // Mark the Command as a SPROC
        myCommand.CommandType = CommandType.StoredProcedure;

        // Open the database connection and execute the command
        myConnection.Open();
        SqlDataReader dr = myCommand.ExecuteReader();

        // Return the datareader
        return dr;
    }
}

【问题讨论】:

标签: c# sql asp.net data-binding dispose


【解决方案1】:

你用来绑定数据的代码使用了using

using (SqlDataReader allUsersDataSource = AdminDB.GetUsers())
   {
    // bind all portal users to dropdownlist
     allUsers.DataSource = allUsersDataSource;
     allUsers.DataBind();
   }

using 只接受 IDisposable 对象并在块执行结束时调用 Dispose 方法。因此,您不必担心在此处处理 Reader 对象。

【讨论】:

  • 我知道我正在关闭 DataReader。但是 DataBind 是否需要让 SqlDataReader 仍然“活着”才能工作,或者数据绑定是否保存了信息并且不再需要 datareader?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-03-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-11-26
  • 2011-09-04
  • 2010-09-19
相关资源
最近更新 更多