C# – error ‘there is already an open datareader associated with this command which must be closed first’

ado.netc

runtime error 'there is already an open datareader associated with this command which must be closed first'

objCommand = new SqlCommand("SELECT field1, field2 FROM sourcetable", objConn);

objDataReader = objCommand.ExecuteReader();

while (objDataReader.Read())
{
objInsertCommand = new SqlCommand("INSERT INTO tablename (field1, field2) VALUES (3, '" + objDataReader[0] + "')", objConn);
objInsertCommand.ExecuteNonQuery();//Here is the error
}
objDataReader.Close();

I cannot define any stored procedure here.
Any help would we appreciated.

Best Answer

No need to do all that, just turn on MARS and your problem will get solved. In your connection string just add MultipleActiveResultSets=True;

Related Topic