ddlUsers.DataSource = ScrapDB.GetUsers(); ddlUsers.DataTextField = "UserID"; ddlUsers.DataBind(); ScrapDB.CloseReader(); // Call CloseReader in Data Class now that ddl is populatedData Class
//using System; using System.Configuration; using System.Data; using System.Data.SqlClient; //namespace eScrap_C.Classes namespace eScrap_C { /// <summary> /// Summary description for ScrapDB. /// </summary> /// public class ScrapDB { private static SqlDataReader UsersReader; // Declare SqlDataReader here and not in GetUser() public static SqlConnection GetConnection() { string connectionString = ConfigurationSettings.AppSettings["connectionString"]; return new SqlConnection(connectionString); }Notice the GetConnection method has been referenced below as Users and that the connection is closed before the RETURN
public static DataTable GetUsers1() { // Use a DataTable to fill ddlUsers... string selectStatement = "SELECT UserID " + "FROM UserInfo ORDER BY UserID"; SqlConnection Users = GetConnection(); SqlCommand selectCommand = new SqlCommand(selectStatement, Users); SqlDataAdapter daUsers = new SqlDataAdapter(); daUsers.SelectCommand = selectCommand; DataSet dsUsers = new DataSet(); daUsers.Fill(dsUsers, "UserInfo"); Users.Close(); return dsUsers.Tables["UserInfo"] ; } public static SqlDataReader GetUsers() { // Use a SqlDataReader to fill ddlUsers... string selectStatement = "SELECT UserID " + "FROM UserInfo ORDER BY UserID"; SqlConnection UsersConnection = GetConnection() ; UsersConnection.Open(); SqlCommand selectCommand = new SqlCommand(selectStatement, UsersConnection); UsersReader = selectCommand.ExecuteReader(CommandBehavior.CloseConnection); UsersReader.Read(); return UsersReader; } public static void CloseReader() { UsersReader.Close(); } } }Randy had the right idea. You cannot close the SqlDataReader before the ddl is filled. You must close it after the ddl is populated.