我可以在DataBind()之后关闭一个SqlDataReader

时间:2014-08-28 18:39:21

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

说我做这样的事情

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;
    }
}

1 个答案:

答案 0 :(得分:0)

用于绑定数据的代码使用使用

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

using仅使用IDisposable对象,并在块执行结束时调用Dispose方法。所以你不必担心在这里处理Reader对象。