Microsoft KB Archive/318137

= Error message when you execute the ChangeDatabase method of a Connection object: &quot;ChangeDatabase requires an open Connection&quot; =

Article ID: 318137

Article Last Modified on 3/13/2006

-

APPLIES TO


 * Microsoft .NET Framework 1.1 Service Pack 1
 * Microsoft ADO.NET 2.0
 * Microsoft Visual Studio .NET 2002 Professional Edition

-



This article was previously published under Q318137



SYMPTOMS
When you execute the ChangeDatabase method of a Connection object, you may receive the following error message:

An unhandled exception of type 'System.InvalidOperationException' occurred in system.data.dll

Additional information: ChangeDatabase requires an open Connection. The connection's current state is Open.

If you are using Microsoft ADO.NET 2.0 in Microsoft Visual Studio 2005, you receive the following error message:

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



CAUSE
This error occurs because the DataReader object uses the Connection object exclusively. If the DataReader is still open, you cannot carry out any commands for the connection, including the ChangeDatabase method.



RESOLUTION
To resolve this problem, make sure that you close the DataReader before you call the ChangeDatabase method.



STATUS
This behavior is by design.



Steps to reproduce the behavior
 Start Visual Studio .NET. Create a new Windows Application project in Visual Basic .NET. Form1 is added to the project by default. Place a Button control on Form1. Change the Name property of the button to btnTest .  Add the following code to the &quot;General Declarations&quot; section of Form1 so that you are not required to qualify declarations in this namespace later in your code: Imports System.Data.SqlClient   Add the following code in the btnTest_Click event: Dim dr As SqlDataReader Dim con As New SqlConnection(&quot;server=myServer;user id=myUID;&quot; & _                                    &quot;password=myPWD;database=northwind&quot;) con.Open Dim cmd As New SqlCommand(&quot;select * from customers&quot;, con) dr = cmd.ExecuteReader While dr.Read 'process data End While con.ChangeDatabase(&quot;pubs&quot;) dr.Close con.Close </li> Modify the connection string as appropriate to connect to your server.</li> Save and then run the project.</li> Click btnTest. Notice that you receive the error message that is listed in the &quot;Symptoms&quot; section.</li></ol>

<div class="resolution_section">

RESOLUTION
<ol>  Locate the following code in Form1: con.ChangeDatabase(&quot;pubs&quot;) dr.Close Reverse the order of these lines of code as follows: dr.Close con.ChangeDatabase(&quot;pubs&quot;) </li> Save and then run the project.</li> Click btnTest. Notice that you do not receive the error message.</li></ol>

<div class="references_section">