Data Reader

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • =?Utf-8?B?SGVsZW4gVHJpbQ==?=

    #1

    Data Reader

    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.ExecuteReade r();
    if (dr.Read())
    {
    intPatientCount =1;
    strPatNo = Convert.ToStrin g(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

  • Ben Voigt

    #2
    Re: Data Reader


    "Helen Trim" <Helen Trim@discussion s.microsoft.comwrote in message
    news:99F84AAB-2684-4FB4-9FC5-AB0B7399C5F2@mi crosoft.com...
    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.ExecuteReade r();
    if (dr.Read())
    {
    intPatientCount =1;
    strPatNo = Convert.ToStrin g(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
    >

    Comment

    Working...