0

I am currently facing a bizarre issue when running the following code on a single laptop (other environments are not experiencing the issue).

I create a SqlDataReader with CommandBehavior.SequentialAccess set, and attempt to read the first column of data.

using (SqlDataReader theReader = GetReader(theSQLConnection))
{
   if (theReader.HasRows && theReader.Read())
   {
      shortID = (short)theReader[MyConstants.SHORT_ID_COLUMN_NAME];
      ...

When my code runs, I get an error:

Attempt to read from column ordinal '0' is not valid. With CommandBehavior.SequentialAccess, you may only read from column ordinal '1' or greater.

However, if I put a breakpoint on the opening curly brace of the if statement, and then in the immediate window, type

(short)theReader[MyConstants.SHORT_ID_COLUMN_NAME]

then the value prints out in the immediate window as expected.

If I restart debugging and put the breakpoint on the shortID = ... line, then I get the exception message when trying the same thing in the immediate window.

It doesn't appear that there should be anything advancing the reader between the curly brace and the first read, but that is what the exception message is suggesting.

0

2 Answers 2

2

The issue happens because you are in debug mode. When you are debugging make sure you have your Autos window closed. The Autos window automatically reads from the datareader when the statement is highlighted, thereby advancing your ordinal index. So when you execute the statement, the reader already advanced to the next ordinal.

Sign up to request clarification or add additional context in comments.

Comments

0

see - https://support.microsoft.com/en-us/kb/308614

you can access fields only once and in sequence of you SQL only

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.