Data Reader

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

Guest

Is there any way to know how many records a data reader returns, without
having to read each one and increment a counter?

I am creating an ASP.NET 2.0 project in C#.

I need to read data from the first record, if there is only one and count
them if there is more than one. The code that I have written looks like this:

dr = cd.ExecuteReader();
if (dr.Read())
{
intPatientCount=1;
strPatNo = Convert.ToString(dr["pat_no"]); // Store the pat_no in
case there is only one
while (dr.Read())
{
intPatientCount++;
}
}
dr.Close();

It works, but it's not very elegant or efficient. Can anyone suggest a
better way?

Thanks,
Helen
 
Helen Trim said:
Is there any way to know how many records a data reader returns, without
having to read each one and increment a counter?

I am creating an ASP.NET 2.0 project in C#.

I need to read data from the first record, if there is only one and count
them if there is more than one. The code that I have written looks like
this:


In general, I don't know of a better way. However, if you are dealing with
database access, it may be far more efficient to run a "SELECT COUNT(*)
WHERE...." query first to get the count, then get the actual data only if
the count is 1.
dr = cd.ExecuteReader();
if (dr.Read())
{
intPatientCount=1;
strPatNo = Convert.ToString(dr["pat_no"]); // Store the pat_no in
case there is only one
while (dr.Read())
{
intPatientCount++;
}
}
dr.Close();

It works, but it's not very elegant or efficient. Can anyone suggest a
better way?

Thanks,
Helen
 
Back
Top