Invalid attempt to FieldCount when reader is closed error

  • Thread starter Patrick Olurotimi Ige
  • Start date
P

Patrick Olurotimi Ige

Why do i get "Invalid attempt to FieldCount when reader is closed"

Is the problem the way the datareader reads data as
opposed to a dataset?

When trying to compile this code:-

Dim reader As IDataReader = GetReader()

Dim chart As New LineChart()
chart.DataXValueField = "Product"
chart.DataYValueField = "Price"
chart.DataSource = reader
chart.DataBind()
reader.Close()
ChartControl1.Charts.Add(chart)

Dim chart1 As New LineChart()
chart1.DataSource = reader
chart1.DataXValueField = "Product2"
chart1.DataYValueField = "Price2"
Getting the error here---> chart1.DataBind()
ChartControl1.Charts.Add(chart1)

reader.Close()
ChartControl1.RedrawChart()

With the function:-
Function GetReader() As IDataReader

Dim connection As new OleDbConnection("")

Dim command As new OleDbCommand("SELECT Top 10 [ProductName] As
Product,[UnitPrice] As Price, [UnitsInStock] As Stock FROM Products
order by UnitPrice desc", connection)
connection.Open()

Return command.ExecuteReader(CommandBehavior.CloseConnection)

End Function
 
K

Karl Seguin

Patrick:
Return command.ExecuteReader(CommandBehavior.CloseConnection)

closes the connection after ExecuteReader() is called and thus closing the
datareader (the datareader is tied to the connection). You must either keep
the connection open and close it and the reader when you are done with it,
or make use of a dataset.

Personally I'd recommend you use the DataSet because then you end up with a
situation where 1 function (GetReader()) creates your connnection and opens
it, whereas calling function is responsible for cleaning up that
resource...definetly messy....Another solution would be to pass the
connection in as a parameter to GetReader() but I'd still favour DataSets
over this...

Karl


--
MY ASP.Net tutorials
http://www.openmymind.net/index.aspx - New and Improved (yes, the popup is
annoying)
http://www.openmymind.net/faq.aspx - unofficial newsgroup FAQ (more to
come!)
 
P

Patrick Olurotimi Ige

Thanks Karl for the response.
I did a research too and now i know the limitations of DataReader!
I'll implement using DataSet..
Thanks
Patrick
 

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

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,582
Members
45,065
Latest member
OrderGreenAcreCBD

Latest Threads

Top