Level Extreme platform
Subscription
Corporate profile
Products & Services
Support
Legal
Français
Still trying to resolve errors using C# and a dataclass
Message
General information
Forum:
ASP.NET
Category:
Web forms
Environment versions
OS:
Windows 2000 SP4
Network:
Windows 2000 Server
Database:
MS SQL Server
Miscellaneous
Thread ID:
00956670
Message ID:
00956731
Views:
9
My thanks to everyone! There is also an example using a DataTable. The SqlDataReader is what I wanted to conquer! :)


This works

Form Codebehind
                        ddlUsers.DataSource = ScrapDB.GetUsers();
			ddlUsers.DataTextField = "UserID";
			ddlUsers.DataBind();

			ScrapDB.CloseReader();  // Call CloseReader in Data Class now that ddl is populated
Data 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.

Tom
Previous
Reply
Map
View

Click here to load this message in the networking platform