.NET Tutorials, Forums, Interview Questions And Answers
Welcome :Guest
Sign In
Win Surprise Gifts!!!

Post New Web Links

DataReader.Read closed premeturely

Posted By:      Posted Date: September 15, 2010    Points: 0   Category :ASP.Net
HiI noticed a very strange thing. I was debugging the following code, and thus had put the breakpoint at line: using (IDataReader dataReader = db.ExecuteReader(dbCommand)). dataReader was getting populated, but after a halt of lets say 30 seconds, dataReader was emptied, while I was debugging.So when control went to dataReader.Read(), i got error: "Invalid attempt to call FieldCount when reader is closed".But if i execute the function at one go, without halting at dataReader line (without breakpoint), it works alright.My question is what is triggering the dataReader to close ?Its a legacy code, and have worked fine. Database db;db = DatabaseFactory.CreateDatabase(); db.AddInParameter(dbCommand, "ID", DbType.String, ID);                 do                 {                     try                     {                         using (IDataReader dataReader = db.ExecuteReader(dbCommand))                         {                             while (dataR

View Complete Post

More Related Resource Links

Linq2Sql error: "Invalid attempt to call Read when reader is closed."


I've read up on this error from other posts and on other sites, but haven't found a solid resolution to the issue yet. My setup is as follows:

I have a RepositoryBase class that fields certain db calls that all repositories need to perform. In one such call, "GetSecurityGroup", it works most of the time, but will seemingly at random throw an exception with the error "Invalid attempt to call Read when reader is closed." All other Repository classes inherit from this one, and they all use the same DataContext object, which I understand isn't thread safe. Since there could be multiple calls to the DataContext object on the same page, perhaps one is using the DataContext when the next tries to do so. I'm not sure. What can I do to ensure this doesn't happen?

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


when i insert record

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

help me.

SqlConnection conn = new SqlConnection(@"Data Source=Localhost\SQLEXPRESS;Initial Catalog=StudentDetails;Integrated Security=True");

SqlCommand cmd2 = new SqlCommand();
SqlCommand cmd1 = new SqlCommand();

if (conn.State == ConnectionState.Closed)

cmd2 = new SqlCommand("Select * from UserInfo where Standard", conn);
            SqlDataReader dr1 = cmd2.ExecuteReader();
            string stu, par,std,sec,roll;
            par = "";
            stu = "";
            std = "";

DataReader or DataSet to read an output parameter not essential?


I always thought we had to use a DataReader or a Dataset to read a given SQL data but i realized that it is not necessary to use them to read an SQL Output Parameter (im not a SQL expert).

AM i right???
Is it okay to do it that way?
Is it faster than using a DataReader?




Dim myConnectionDB As New SqlConnection(DbWrite)
Dim myCommand As SqlCommand = New SqlCommand("_AddUsers", myConnectionDB)

myCommand.CommandType = CommandType.StoredProcedure

myCommand.Parameters.Add(New SqlParameter("@UserId", SqlDbType.VarChar))
myCommand.Parameters("@UserId").Value = UserId

.... others parameters ...

myCommand.Parameters.Add(New SqlParameter("@RowCount", SqlDbType.Int))
myCommand.Parameters("@RowCount").Direction = ParameterDirection.Output

        Dim rowsaffected As Integer


Why do I get: There is already an open DataReader associated with this Command which must be closed



I create a Form and show it:

            JelentesForm jf = new JelentesForm(Globals.DC, (int)row.Cells["Jelentes_ID"].Value);
            jf.StartPosition = FormStartPosition.CenterParent;

The form gets the DataContext (DC) and the ID of row in a table to work with.

In the constructor the form reads the row, then validates it:

            var jel = from j in context.JELENTES where j.Jelentes_ID == Jelentes_ID select j;
            jelentes = jel.Single();


The validating means calling the same stored procedure for the fields to check them. The stored procedure reads data from other tables for checking.

When I open the form first time it is all right. When I close the form (without any action) and open it second time I get the error above in the validateAll() on the first call of stored procedure.

I tried to move the validateAll() from constructor into form_Shown event, then tried to move it into a

There is already an open DataReader associated with this Command needs to be Closed



Hope this subject seems to be familiar in search. I need this subject to be taken for a discussion to get the right solution for me.

My scenario:

I am using  a web service which access the sql server database to provide an XML output. this part is working fine. I am using a SqlDataAdapter and DataTable with Fill method to get the data.


When more than one person access this web service at the same time i get the error message which is given in the subject line.

I understand the problem is because of the sql connection which is still open by the first user. If the first user completes his operation before the second users request then both the user receives the correct response.

My Solution:

What i did was i initiated 10 connection strings and will check which connection string is closed and i have used this connection for the second persons request if they both access at the same time.

My Question:

I know this is not the best solution. So i want to take this topic to be discussed to get a right solution. I am in need of some idea from the experts in this forum to resolve my issue.


Thanks & Regards

Karthikeyan S


Trying to read closed Excel file.



I am trying to read Excel file in VB.NET with the following provider

Provider=Microsoft.Jet.OLEDB.4.0;Data Source=c:\temp\Bok1.xlsx;Extended Properties=""Excel 8.0;HDR=YES;""
But the problem is - with this provider I can read an .xlsx file when it is opened in Office Excel Application but when i close

the application i cant read the file and get the following exception on connection invoke.

The external table has a different format than expected.

Serial Port Communication Read and Write using C#.net

In this simple article you will learn that how you can Open and read COM port data using System.IO.Ports Namespace.
Simply just create New Project of windows application in C#.

Import ServiceProcess APIs
using System.IO.Ports

Imports System.IO.Ports

Write Parsing functions which parse port data according to attached device

Scripts not read when in head tag


I just upgraded to VS2010 if that matters.  I'm learning JQuery and noticed that scripts don't work if they're in the head tag.  Also, I need the script tag with type="text/javascript" in the head (with nothing else) in order for the JQuery scripts in the body to work.

Very bizzare, any suggestions?

With a separate script tag in the <body> with my JQuery script, this works

<head runat="server">
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js" />
<script type="text/javascript">

This doesn't:

<head runat="server">
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js" />

I am not able to read xml file with XDocument if its Descendants has Attribute xmlns="http://abc.co


I am not able to read xml file with XDocument if its Descendants has  Attribute like:-

<?xml version="1.0" encoding="utf-8" standalone="yes"?>
  <row ID="1" xmlns="http://www.opentravela.org/OTA/2003/05">
    <var country_name="Caribbean and Rest of the world" city_name="Kingston" flight_category="Economy Class" via="Atlanta" flight_departure="London Heathrow" airline_logo="Delta" adult_fare="Delta" child_fare="660" infant_fare="561" date1="132" date2="2010-08-15" />


I don't know what to do ?

Looking for some help..

How to read XML using LINQ in VB.NET


Can someone please tell me (sample code) how to read this XML into a SQL DB?  Should I use LINQ to XML?  Does anyone have any sample code?  I am working in VB.NET


<?xml version="1.0" encoding="utf-8"?>

<ReadOrderResponseType xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">

<Status xmlns="urn:mysol:apis">Success</Status>

<TimeStamp xmlns="urn:mysol:apis">2010-07-25T15:26:49.1150235Z</TimeStamp>

<StoreUrl xmlns="urn:mysol:apis">http://xyz.COM</StoreUrl>

<PageResponse xmlns="urn:mysol:apis">




Read Excel file from Web Application (C#)



I have a web app where user uploads a file.

File is saved in server locally and I want to read some data from it.

Currently my development  server has office 2003.

So do I need office 2007 in order to be able to  read an excel from office 2007 ?

What are other requirements  ?

I tried a test, using

Microsoft.Office.Interop.Excel.Application excelApp = new Microsoft.Office.Interop.Excel.Application();
Microsoft.Office.Interop.Excel.Workbook wrkBook; // = new Microsoft.Office.Interop.Excel.Workbook();

wrkBook = excelApp.Workbooks.Open(@"C:\www\excel_files\b.xls", ....);

But When trying to open the file I get the error:

Exception from HRESULT: 0x800A03EC

So I'm wondering what I'm missing.


How to read value of CheckBox in EXCEL sheet


I am using OLEDBConnection (@"Provider=Microsoft.ACE.OLEDB.12.0;") to connect to the EXCEL file and read contents. When I read the contents, I get all the contents from the excel sheet but i dont get contents for checkboxes placed inside.

My Excel sheet contains set of checkboxes and I need to know If they are checked or not.These checkboxes are controls which are added from Developer tab in EXCEL.

I dont want to use Excel Assemblies for reading contents as it is not recommended. And also i am using OLEDBconnection and want to stick to this .

Awaiting replies from you guys. Thanks in Advance.

How to read Excel table?


If I  use Microsoft.Jet.OLEDB.4.0 to retreive for example named range or sheet from Excel and use it as data source for some server control on the ASP page, everything works fine. But when I try to get table from Excel like this: "select * from [Table1]", debugger complains that database engine could not find object Table1. So how should I reference Table1 in Excel file so that the database engine could find it?

How to read the custom http header



I have just joined the forum. I have a very simple query. I have added custom header to my website. Now I want to read the custom header. I am using IIS 6.0 on windows XP. I have already tried using using the Request.ServerVariables and and Request.header method. But none of them give me the custom header added to website.

Can any body help?

Thanks a lot in advance



Can't read global resource in asp button


I have translated Text Ok in arabic and I have that placed in global Navig.resx file

<asp:Button ID

Crystal Report gives System.AccessViolationException: Attempted to read or write protected memory. T


when a crystal report for same id is opened again at same time or refreshed then it gives the

"System.AccessViolationException: Attempted to read or write protected memory. This is often an indication that other memory is corrupt."

Stack Trace is :-

Stack Trace:

[AccessViolationException: Attempted to read or write protected memory. This is often an indication that other memory is corrupt.]
CrystalDecisions.ReportAppServer.Controllers.DatabaseControllerClass.SetConnectionInfos(ConnectionInfos ConnectionInfos) +0
CrystalDecisions.CrystalReports.Engine.Table.ApplyLogOnInfo(TableLogOnInfo logonInfo) +362
CrystalDecisions.CrystalReports.Engine.ReportDocument.SetTableLogon(Tables tables, String user, String password, String server, String database, Boolean ignoreCase) +258
CrystalDecisions.CrystalReports.Engine.ReportDocument.SetDatabaseLogon(String user, String password, String server, String database, Boolean ignoreCase) +204

How to create a read only accessor


I have created getter setters before. But how do I make a read only accessor in VB.net? I want a value to be read, but not to be set. 

ASP.NetWindows Application  .NET Framework  C#  VB.Net  ADO.Net  
Sql Server  SharePoint  Silverlight  Others  All   

Hall of Fame    Twitter   Terms of Service    Privacy Policy    Contact Us    Archives   Tell A Friend