Microsoft Knowledge Base Email Alertz

KBAlertz.com: When you use

Receive Microsoft Knowledge Base articles by E-Mail?

Every night we scan the Microsoft Knowledge Base. If technologies you're interested in are updated, we'll send you an e-mail. You only get one e-mail a day, and only when new articles are added.

Click here to create a
FREE account
Already have an account?
[Click here to Login]

Search KbAlertz

Advanced Search

Webmasters
Put kbAlertz on your website.
[ Click Here for more! ]





ASP.NET 3.5 Web Hosting with Windows 2008 and SQL 2008: Click Here!
Discount ASP.NET Hosting
ASP.NET 2.0 and 3.5
Windows2008 and SQL2008
US and UK Hosting
The ad says 3 - but KBAlertz referrals get
** SIX MONTHS FREE **


Bug Tracking Software
For bug tracking software or defect tracking software or issue tracking software, visit Axosoft.


Community Site



We Send hundreds of thousands of emails using ASP.NET Email



Expert Web Design & Graphic Design
Design44.com

ASP.NET 3.5 Web Hosting with Windows 2008 and SQL 2008: Click Here!
Discount ASP.NET Hosting
ASP.NET 2.0 and 3.5
Windows2008 and SQL2008
US and UK Hosting
The ad says 3 - but KBAlertz referrals get
** SIX MONTHS FREE **




Mentioned In








Microsoft Knowledge Base Article

This article contents is Microsoft Copyrighted material.
©2005-©2007 Microsoft Corporation. All rights reserved. Terms of Use | Trademarks




Article ID: 308614 - Last Review: December 11, 2006 - Revision: 2.5

An "Invalid attempt to read from column ordinal" error occurs when you use DataReader in Visual C#

This article was previously published under Q308614
For a Microsoft Visual Basic .NET version of this article, see 308069  (http://kbalertz.com/Feedback.aspx?kbNumber=308069/EN-US/ ) .

This article refers to the following Microsoft .NET Framework Class Library namespace:
  • System.Data.SqlClient

On This Page

SYMPTOMS

When you use DataReader to read a row, if you try to access columns in that row, you receive an error message that resembles the following:
System.InvalidOperationException: Invalid attempt to read from column ordinal '0'. With CommandBehavior.SequentialAccess, you may only read from column ordinal '2' or greater.

CAUSE

This problem occurs because you executed OleDbCommand or SqlCommand with the System.Data.CommandBehavior.SequentialAccess flag set but did not access the columns sequentially.

RESOLUTION

Use one of the following methods to work around this problem:
  • Read each column only once and in the sequence in which it is defined by the SELECT query.

    NOTE: For performance reasons, which are listed in the "More Information" section, this is the preferred resolution.
  • Do not use CommandBehavior.SequentialAccess. If you do not use CommandBehavior.SequentialAccess, you can access a column in a row twice and read columns out of sequence.

STATUS

This behavior is by design.

MORE INFORMATION

Setting the CommandBehavior.SequentialAccess flag causes the DataReader to read both rows and columns sequentially. The rows and columns are not buffered. After you read past a column, it is dropped from memory. Any attempt to re-read the column or read previously read columns results in an exception.

Using the CommandBehavior.SequentialAccess flag provides a performance benefit, especially when using Binary Large Object (BLOB) fields. If you do not use SequentialAccess, all the BLOB data is copied to the client. This can consume a lot of resources.

CommandBehavior.SequentialAccess also improves performance when accessing non-BLOB fields. When CommandBehavior.SequentialAccess is not set, you can access a column out of order; however, you incur the following overhead:
  • The column is checked to see if the column is later than a previous accessed column.
  • The data for all of the previously accessed columns is retrieved and then cached for potential later retrieval.
Columns must be checked and cached because when you use the DataReader, the underlying stream is forward-only for rows as well as column access.

Steps to reproduce the behavior

This sample uses the Northwind database that comes with Microsoft SQL Server.
  1. In Visual Studio .NET, create a new Visual C# Windows Application. Form1 is added to the project by default.
  2. Add a Button control to Form1; Button1 is added by default.
  3. Open the code window for Form1 and then paste the following code at the top of the code window:
    using System.Data;
    using System.Data.SqlClient;
    					
  4. Open the code window for Button1 and paste the following code into the button1_Click event procedure:
    SqlConnection myConnection = new SqlConnection();
    
    // Modify this connection string to use your SQL Server and logins.
    myConnection.ConnectionString = "Server=server;uid=login;pwd=password;database=northwind";
    			
    SqlCommand myCommand = new SqlCommand();
    myCommand.CommandText = "SELECT FirstName, LastName FROM Employees";
    		
    myConnection.Open();
    
    myCommand.Connection = myConnection;
    // SequentialAccess gives forward-only reading of columns
    SqlDataReader myReader = myCommand.ExecuteReader(CommandBehavior.SequentialAccess);
    
    //Uncomment the following line, and comment the preceding line to work around.
    //SqlDataReader myReader = myCommand.ExecuteReader();
    try {
    	// Read only the first row.
    	myReader.Read();
    
    	// Display the LastName and then the FirstName of the row.
    	MessageBox.Show(myReader["LastName"].ToString() + ", " + myReader["FirstName"].ToString());
    
    	// Uncomment the following line, and comment the preceding line to work around.
    	//MessageBox.Show(myReader["FirstName"].ToString() + " " + myReader["LastName"].ToString());
    	}
    catch (System.Exception ex) { 
    	MessageBox.Show(ex.ToString());
    	}
    finally 
    	{
    	// Always call Close when done reading.
    	myReader.Close();
    	myConnection.Close();
            }
  5. Modify the following line:
    myConnection.ConnectionString = "Server=server;uid=login;pwd=password;database=northwind";
    						
    to use your SQL Server server name and login.
  6. With the CommandBehavior.SequentialAccess flag set, try to access the columns out of sequence as follows:
    1. Press F5 to compile and run the client application. Note the error that is displayed.
    2. Click OK to dismiss the error. Stop the running project to return to the design environment.
  7. With the CommandBehavior.SequentialAccess flag set, try to access the columns in the sequence that they are defined in the SELECT statement as follows:
    1. Uncomment the following line
         //MessageBox.Show(myReader["FirstName"].ToString() + " " + myReader["LastName"].ToString());
    2. Comment the line
         MessageBox.Show(myReader["LastName"].ToString() + ", " + myReader["FirstName"].ToString());
      						
    3. Press F5 to compile and run the client application. The column data is displayed without error.
    4. Click OK to dismiss the message box. Stop the running project to return to the design environment.
  8. With the CommandBehavior.SequentialAccess flag not set, try to access the columns out of sequence as follows:
    1. Comment the lines
      SqlDataReader myReader = myCommand.ExecuteReader(CommandBehavior.SequentialAccess);
      						
      -and-
      MessageBox.Show(myReader["FirstName"].ToString() + " " + myReader["LastName"].ToString());
      						
    2. Uncomment the lines
      //SqlDataReader myReader = myCommand.ExecuteReader();
      -and-
      MessageBox.Show(myReader["LastName"].ToString() + ", " + myReader["FirstName"].ToString());
      						
    3. Press F5 to compile and run the client application. The column data is displayed without error.
    4. Click OK to dismiss the message box. Stop the running project to return to the design environment.

REFERENCES

For more information, see the "SequentialAccess enumeration member" topic in the Visual Studio .NET Help documentation.

APPLIES TO
  • Microsoft ADO.NET 2.0
  • Microsoft ADO.NET (included with the .NET Framework)
  • Microsoft Visual C# .NET 2002 Standard Edition
  • Microsoft Visual C# .NET 2003 Standard Edition
  • Microsoft Visual C# 2005
Keywords: 
kbtshoot kberrmsg kbdatabase kbprb kbsqlclient kbsystemdata KB308614
       

Community Feedback System

Very often, it takes hours to solve a problem. Very often, you've looked high and low, and have tried a lot of solutions. When you finally found it, chances are, it was because someone else helped you. Here's your chance to give back. Use our community feedback tool to let others know what worked for you and what didn't.

Please also understand that the community feedback system is not warranted to be correct, it's simply a system that we've built to let people try and help each other. If something in a feedback response doesn't make sense to you, or you're not comfortable making changes that the feedback talks about (like registry edits), please consult a professional.

Thank you for using kbAlertz.com Feedback System.

-- Scott Cate

Be the first to leave feedback, to help others about this knowledge base article.

(Optional) Name

(Optional) Public URL Or Email

Comments
No HTML -- Text Only Please