473,749 Members | 2,546 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

SqlDataReader problem...

Hi, when I call ExportData I have this error:

Invalid attempt to Read when reader is closed.

Telling me that there's a problem with this line:
while(_dataR.Re ad()){

Code:
*************** *************** *************** ****
public void Export2CSV(){
SqlDataReader _dataR = ExportData();
while(_dataR.Re ad()){
//using data
}
}
private SqlDataReader ExportData(){
//Data extraction from database
return myDataR;
}
*************** *************** *************** ****
Nov 16 '05 #1
7 2362
Hi,

It seems fine to me, as long as you do not close the datareader in
ExportData() it should be fine.
Post the code inside ExportData to see if there is a problem there.

cheers,

--
Ignacio Machin,
ignacio.machin AT dot.state.fl.us
Florida Department Of Transportation

"Franck Diastein" <fd*******@eusk altel.net> wrote in message
news:e0******** ******@TK2MSFTN GP11.phx.gbl...
Hi, when I call ExportData I have this error:

Invalid attempt to Read when reader is closed.

Telling me that there's a problem with this line:
while(_dataR.Re ad()){

Code:
*************** *************** *************** ****
public void Export2CSV(){
SqlDataReader _dataR = ExportData();
while(_dataR.Re ad()){
//using data
}
}
private SqlDataReader ExportData(){
//Data extraction from database
return myDataR;
}
*************** *************** *************** ****

Nov 16 '05 #2
You are probably closing the underlying connection associated with the
SqlDataReader before returning the SqlDataReader from the ExportData method.
Please post a snippet of code with the implementation of that particular
method.

--
venlig hilsen / with regards
anders borum
--
Nov 16 '05 #3
private SqlDataReader ExportData(){
SqlDataReader myDataR = null;
try {
m_DB.DBParamIni t();
m_DB.DBParamAdd ("@ID", mintID, SqlDbType.BigIn t);
myDataR = m_DB.DBExecRead erSP("SP_GetInf o");
return myDataR;

}
catch( SqlException e ) {
throw new Exception( e.Message );
}
finally {
myDataR.Close() ;
myDataR = null;
}
}

I want to be able to close and destruct myDataR even if an error ocurred...

How can I do it ?

TIA

Franck Diastein wrote:
Hi, when I call ExportData I have this error:

Invalid attempt to Read when reader is closed.

Telling me that there's a problem with this line:
while(_dataR.Re ad()){

Code:
*************** *************** *************** ****
public void Export2CSV(){
SqlDataReader _dataR = ExportData();
while(_dataR.Re ad()){
//using data
}
}
private SqlDataReader ExportData(){
//Data extraction from database
return myDataR;
}
*************** *************** *************** ****

Nov 16 '05 #4
Hi Franck,

As Ignacio and Anders write before, you were closing data
reader before you want to use it.

There's no sense to return closed IDataReader.
If you don't want to keep it open then return
whole records as a DataTable or an ArrayList.

Regards
Marcin
private SqlDataReader ExportData(){
SqlDataReader myDataR = null;
try {
m_DB.DBParamIni t();
m_DB.DBParamAdd ("@ID", mintID, SqlDbType.BigIn t);
myDataR = m_DB.DBExecRead erSP("SP_GetInf o");
return myDataR;

}
catch( SqlException e ) {
throw new Exception( e.Message );
}
finally {
myDataR.Close() ;
myDataR = null;
}
}

I want to be able to close and destruct myDataR even if an error ocurred...

How can I do it ?

TIA

Franck Diastein wrote:
Hi, when I call ExportData I have this error:

Invalid attempt to Read when reader is closed.

Telling me that there's a problem with this line:
while(_dataR.Re ad()){

Code:
*************** *************** *************** ****
public void Export2CSV(){
SqlDataReader _dataR = ExportData();
while(_dataR.Re ad()){
//using data
}
}
private SqlDataReader ExportData(){
//Data extraction from database
return myDataR;
}
*************** *************** *************** ****

Nov 16 '05 #5
Hello!

The SqlDataReader is a low level provider that works by retrieving one row
at a time on a active connection to the database. This allows the
SqlDataReader to work with really large resultsets, because it doesn't have
to move all the data from the datastore to the client before processing can
start (as is the case with the DataSet, which in fact is populated with the
DataAdapter that uses a DataReader internally).

Closing the SqlDataReader is therefore not an option, if you need to pass it
from a method. I see your frustration in the lack of control of how and when
the resources associated with the SqlDataReader are disposed.

When creating the SqlDatader, pass an appropriate CommandBehavior
enumeration value to the sqlCommand.Exec uteReader() method (for instance
CommandBehavior .CloseConnectio n).

From the MSDN:
When the command is executed, the associated Connection object is closed
when the associated DataReader object is closed.

This means that once the consumer of the SqlDataReader reached the last row
and closes the SqlDataReader, the underlying connection is closed as well
and returned to the pool.

Exposing a SqlDataReader allows for low level access to the database but
comes with a price. Using the enumeration as described above can help with
the resource management. I also advice you to wrap the SqlDataReader in a C#
"using" statement, by which the disposing of the SqlDataReader is correctly
handled.

--
venlig hilsen / with regards
anders borum
--
Nov 16 '05 #6
I will try that way...

Thank you all :-)

Marcin Grzębski wrote:
Hi Franck,

As Ignacio and Anders write before, you were closing data
reader before you want to use it.

There's no sense to return closed IDataReader.
If you don't want to keep it open then return
whole records as a DataTable or an ArrayList.

Regards
Marcin
private SqlDataReader ExportData(){
SqlDataReader myDataR = null;
try {
m_DB.DBParamIni t();
m_DB.DBParamAdd ("@ID", mintID, SqlDbType.BigIn t);
myDataR = m_DB.DBExecRead erSP("SP_GetInf o");
return myDataR;

}
catch( SqlException e ) {
throw new Exception( e.Message );
}
finally {
myDataR.Close() ;
myDataR = null;
}
}

I want to be able to close and destruct myDataR even if an error
ocurred...

How can I do it ?

TIA

Franck Diastein wrote:
Hi, when I call ExportData I have this error:

Invalid attempt to Read when reader is closed.

Telling me that there's a problem with this line:
while(_dataR.Re ad()){

Code:
*************** *************** *************** ****
public void Export2CSV(){
SqlDataReader _dataR = ExportData();
while(_dataR.Re ad()){
//using data
}
}
private SqlDataReader ExportData(){
//Data extraction from database
return myDataR;
}
*************** *************** *************** ****

Nov 16 '05 #7
Franck Diastein <fd*******@eusk altel.net> wrote:
Hi, when I call ExportData I have this error:

Invalid attempt to Read when reader is closed.

Telling me that there's a problem with this line:
while(_dataR.Re ad()){

Code:
*************** *************** *************** ****
public void Export2CSV(){
SqlDataReader _dataR = ExportData();
while(_dataR.Re ad()){
//using data
}
}
private SqlDataReader ExportData(){
//Data extraction from database
return myDataR;
}
*************** *************** *************** ****


We'll need to see more code than that.

Could you post a short but complete program which demonstrates the
problem?

See http://www.pobox.com/~skeet/csharp/complete.html for details of
what I mean by that.

--
Jon Skeet - <sk***@pobox.co m>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too
Nov 16 '05 #8

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

3
536
by: Ricola ! | last post by:
Why do I say: SqlDataReader dr; instead of SqlDataReader dr = new SqlDataReader();
2
7404
by: Matthias S. | last post by:
Hi, I've written a simple app which should just fetch some data from a database and render the results into a ListView. In order to not freeze the GUI, I'm using a BackgroundWorker. The arguments for the RunWorkerAsync are the Query to be executed and the Connectionstring. As a result I hoped I could return a SqlDataReader. The problem is, if I create the SqlDataReader within the
3
5889
by: Neil Guyette | last post by:
Hello, Everyone, I'm trying to find information on how to populate a combo box using a SqlDataReader. I want to be able to set the value of the combo's value property different then the combo's text property (what the user will see). Is this possible with a SqlDataReader? Thanks
1
3265
by: Arvind P Rangan | last post by:
Hi All, How do you get all the values of a sqldatareader if it contains multiple resultset. Using sqldatareader.nextresult and sqldatareader.read e.g. While sqldatareader.read ' If not sqldatareader then sqldatareader.nextresult
8
2082
by: bidllc | last post by:
I have a funtion that works fine and dandy when called from anywhere in my app. It will NOT work when called from inside the class in which it resides. This is the function I'm calling: "getProductByID(productID)" from inside another method in the same class. See below. This line throws a null ref exception: While dr.Read() Thanks for any insight!
4
2364
by: mimi | last post by:
Hi Please help me out, I can't find a way to close a sqldatareader when error occur at statement cmd.ExecuteReader(). I can't close it in catch because it is local in try scope and I can't declare it outside try scope either since we have to call cmd.executeReader to create sqldatareader public string GetLogs(int logID) {
4
3236
by: Agnes | last post by:
I got two sub method to check some history record, Now, I found that there is some problem in Sub2() . I think the problem is about the myReader. However, I got no idea to solve it . As Sub2() will be used by another function. I cannot combine them , Please help. Thanks a lot. private Sub Sub1() Dim cmd As New SqlClient.SqlCommand("select invno from arinvinfo , _conn) Dim myReader As SqlDataReader myReader = cmd.ExecuteReader
7
1713
by: Web learner | last post by:
I am trying to create a method GetDataFor(string column) becaues I have to repeat the same statements for several columns but I get an error as follows: The name 'dr' does not exist in the current context It seems the dr -the instance of sqlDataReader - is not becoming available to the method. How to make it available? This seems trivial and newbie problem related to OOP, but I am confused. Could you pl. look at the code or point me to...
3
1310
by: yogarajan | last post by:
hi i am using two sqldatareader. that gives error My code start here SqlConnection conn = new SqlConnection("Data Source=**********;Initial Catalog=****; User Id=****; Password=******"); conn.Open(); //collect all employee// SqlCommand cmd = new SqlCommand("Select * from tblhrims_employeedetail where nvrresigned='no'",conn); SqlDataReader sqldr = cmd.ExecuteReader();
0
8996
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
8832
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
9386
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
9254
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
8255
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
6799
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
4608
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
1
3319
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
3
2217
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.