Odd exception that doesn't make sense to me

  • Thread starter Thread starter Guest
  • Start date Start date
G

Guest

I am getting this exception when running my code:

{"There is already an open DataReader associated with this Command which
must be closed first."}

This is my code:
private Guid CreateCode( string Code )
{
Guid toReturn = Guid.Empty;
this.scCreateCode.Parameters["@Code"].Size = Code.Length;
this.scCreateCode.Parameters["@Code"].Value = Code;
try
{
this.scCreateCode.ExecuteNonQuery();
toReturn = ( Guid )this.scCreateCode.Parameters["@ID"].Value;
}
catch ( Exception ex )
{ //Breakpoint here

}
return toReturn;
}

The point of the failure is obviously:
this.scCreateCode.ExecuteNonQuery();

This isn't returning a DataReader, or using one as far as I know. What is
causing this exception is the calling function which has this code in it:
try
{
results = this.scCheckCode.ExecuteReader();

if ( !results.HasRows )
{
//Calls it here
toReturn = this.CreateCode( Code );
}
else
{
results.Read();
toReturn = ( Guid )results["CodeID"];
}
}

Now why does it matter if I close the DataReader for a seperate SqlCommand
object before running another? Is there a reason for this? Once I change the
code to:
if ( !results.HasRows )
{
results.Close();
results.Dispose();
results = null;
toReturn = this.CreateCode( Code );
}

It works just fine. Both SqCommand objects use the same SqlConnection
object. I am lacking the knowledge for why this works out the way it does,
could someone please shed some light on this?

Thanks,
Chris
 
Hi Chris,

This is a typical exception thrown when trying to do something on a
connection, on which a DataReader has already opened. in .NET 1.1, it
doesn't support to open multiple active result sets on the same opened
connection. You have to close the DataReader first, and then execute the
stored procedure on the same connection. Or you can try to open another
connection object.

Kevin Yu
=======
"This posting is provided "AS IS" with no warranties, and confers no
rights."
 
Back
Top