C#, SQL - multiple rows handling

  • Thread starter Thread starter Guest
  • Start date Start date
G

Guest

I use System.Data.SqlClient.SqlCommand object. I need to fetch data from
database by using SELECT command. the problem is that after calling such
statement in SQL I will get many rows. how to do in my application to get
many rows but acces its content row by row? is it possible to count how many
rows SELECT statement returns?
 
Depends on which method you call; example using ExecuteReader (haven't
tested, but should be OK from memory):

using (IDataReader reader =
cmd.ExecuteReader(CommandBehavior.CloseConnection)) {
// may wish to cast reader as SqlDataReader if Sql, etc
int gridIndex = 0;
do {
int rowIndex = 0;
while (reader.Read()) {
// get values from the reader (either individually or in an
array) and process
rowIndex++;
}
gridIndex++;
} while (reader.NextResult());
}

This handles multiple rows in multiple grids; note that even if you
only expect 1 grid, I recommend reading the grids (all 1 of them) until
you run out of data - as I have seen (in the past) SQL errors thrown
*after* the first grid not be noticed otherwise.

Marc
 

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

Back
Top