4 Replies - 1139 Views - Last Post: 30 January 2012 - 03:25 PM Rate Topic: -----

#1 mb2000inc  Icon User is offline

  • D.I.C Regular
  • member icon

Reputation: 21
  • View blog
  • Posts: 353
  • Joined: 10-November 09

ASP.NET C# SqlDataReader issues....

Posted 19 January 2012 - 12:11 PM

So, creating a data reader:
SqlDataReader reader = cmd.ExecuteReader();


...And beginning a loop with the reader.
while (reader.Read())


and when I step through the code, I get this:

Quote

InvalidOperationException was unhandled by user code
"Invalid attempt to call Read when reader is closed."


Why? And how do I fix it?
Is there something else I can do to "open" the reader?

I've already opened my SqlConnection with:
myConnection.Open();


What am I missing?

Is This A Good Question/Topic? 0
  • +

Replies To: ASP.NET C# SqlDataReader issues....

#2 modi123_1  Icon User is offline

  • Suitor #2
  • member icon



Reputation: 9096
  • View blog
  • Posts: 34,155
  • Joined: 12-June 08

Re: ASP.NET C# SqlDataReader issues....

Posted 19 January 2012 - 12:12 PM

Step through your code.. where? Can we see this method?
Was This Post Helpful? 0
  • +
  • -

#3 mb2000inc  Icon User is offline

  • D.I.C Regular
  • member icon

Reputation: 21
  • View blog
  • Posts: 353
  • Joined: 10-November 09

Re: ASP.NET C# SqlDataReader issues....

Posted 19 January 2012 - 01:46 PM

Actually, I realized that I'm a dork.
I closed the connection within the while loop.
Which means, the reader closed itself with the connection.

So, I moved it out of the loop and it works.

Thanks, though. :)
Was This Post Helpful? 0
  • +
  • -

#4 eclipsed4utoo  Icon User is offline

  • Not Your Ordinary Programmer
  • member icon

Reputation: 1524
  • View blog
  • Posts: 5,960
  • Joined: 21-March 08

Re: ASP.NET C# SqlDataReader issues....

Posted 20 January 2012 - 06:43 AM

You should really be using the using blocks when dealing with SqlConnection and SqlDataReader classes. It will automatically close and dispose of the objects for you, so you don't have to.

example

// you can even stack them like this...
using (SqlConnection cn = new SqlConnection(myConnectionString))
using (SqlCommand cmd = cn.CreateCommand())
{
   cmd.CommandText = "SELECT Name FROM Person";
   
   cn.Open();

   using (SqlDataReader dr = cmd.ExecuteReader())
   {
       while(dr.Read())
       {  
           // do something
       } 
   }
}



After the code runs, the SqlConnection object, SqlCommand object, and SqlDataReader object will be closed and disposed of automatically.
Was This Post Helpful? 1
  • +
  • -

#5 mb2000inc  Icon User is offline

  • D.I.C Regular
  • member icon

Reputation: 21
  • View blog
  • Posts: 353
  • Joined: 10-November 09

Re: ASP.NET C# SqlDataReader issues....

Posted 30 January 2012 - 03:25 PM

You have a valid point. :)
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1