SqlDataReader question

P

PeteZ

I'm having a problem where I exec a stored procedure (which SELECTs all rows
from a table, which has 100 rows) - each row has 8 columns.

When I exec the code (see below) I get 8 in oSQLDR.FieldCount (which I
expect but whenever I try and reference the data in the row
(oSQLDR.GetInt32(0);) I get an exception "invalid attempt to read when no
data is present". If I exec the SP in an ISQL window using: EXEC getEvents,
I get 100 rows returned.

What am I missing here ?


<snip>

oSqlCmd = new SqlCommand();
oSqlCmd.Connection = m_oSqlConnection; // A valid connection Object
is here
oSqlCmd.CommandText = "getEvents";
oSqlCmd.CommandType = CommandType.StoredProcedure;

SqlDataReader oSQLDR = oSqlCmd.ExecuteReader();
int iRows = oSQLDR.FieldCount;
iRowsAffected = oSQLDR.RecordsAffected;

int iID = oSQLDR.GetInt32(0);

<snip>

- peteZ
 
W

Wim Hollebrandse

You need to call the Read() method first on your SqlDataReader object, to
advance to the first row in your result set. Likewise for subsequent
records.

Use a loop to read through all the rows returned, like so:

while (SQLDR.Read())
{
// do something and access SQLDR.GetInt32(0)...
}

Hope that helps.

Cheers,
Wim Hollebrandse
http://www.wimdows.com
http://www.wimdows.net
 

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