Problem with DataReader

V

VB Programmer

I have a data class which returns a datareader. (Using an Access db.) I am
using this method to fill a dropdownlist. The problem is that after I've
ran it one time I get this error:
Could not use ''; file already in use.
I know that the datareader probably has it locked. Where should I close the
datareader?

Here's the function:
Public Function GetDataReader(ByVal strSql As String, ByVal strCnnString
As String) As OleDbDataReader
Dim cnn As New OleDbConnection(strCnnString)
cnn.Open()

Dim result As OleDbDataReader
Dim myCommand As New OleDbCommand
myCommand = New OleDbCommand(strSql, cnn)
result = myCommand.ExecuteReader(CommandBehavior.CloseConnection)

' Return the datareader result
Return result
End Function
 
M

Marina

As soon as you are done reading data from it. Perhaps you shouldn't use
data readers if you are worried about not closing it at the right time, etc.
 
V

VB Programmer

If I close the datareader then the data is not accessible anymore, correct?

I need it to be accessible so that I can read the data into my dropdownlist.
 
M

Miha Markic [MVP C#]

Hi,

But you have to close the datareader when you finished reading from it - so,
you read data from reader and then close it.
The other way would be to use DataTable as a data source
 
M

Marina

You can't have it both ways.

If you need to access a second set of data while keeping the datareader
open, then as Miha said, you should use datatables. Otherwise access
complains about the file being open.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top