listGroups from SQL server, DataReader allready open

  • Thread starter Thread starter Mikael Syska
  • Start date Start date
M

Mikael Syska

Hi,
I have the following code:
static private SqlConnection thisConnection;
[STAThread]
static void Main(string[] args)
{
//
// TODO: Add code to start application here
//

thisConnection = new SqlConnection("Server=BIGBIB; Database=regdb;
Integrated Security=true;");
thisConnection.Open();

listGroups(0);
}

static void listGroups(int id){
SqlCommand thisCommand = new SqlCommand("SELECT * FROM regGroups WHERE
parent = " + id, thisConnection);

SqlDataReader thisReader;

thisReader = thisCommand.ExecuteReader();

while(thisReader.Read()){
Console.WriteLine(" Gruppenavn: {0}, Id: {1}, Added: {2}",
thisReader["name"].ToString(), thisReader["groupId"].ToString(),
thisReader["added"].ToString());
listGroups(Convert.ToInt32(thisReader["groupId"].ToString()));
}
}

I get an Exception, when I run it, that says:
Unhandled Exception: System.InvalidOperationException: There is already
an open
DataReader associated with this Connection which must be closed first.

hmmm, how do I do this? How can I then get all my groups listed???

Hopes theres someone out there that can give me a hint????

thanks
Mikael Syska
 
The problem is probably that you never close the open DataReader. You need
to .Close() the SqlDataReader in listGroups() when you're done using it.
You should also dispose SqlCommand when done, and close and dispose the
SqlConnection.

Thanks,
Michael C., MCDBA
 
Back
Top