0

I have a datareader. I need to find the number of rows in it so that I can instantiate an array. Initially I did this by using:

<code>
DataTable dt = new DataTable();
dt.Load(reader);
int noOfRows = dt.Rows.Count; 
</code>

However I found that loading the reader into the datatable will close the reader before I am able to iterate through it later in my code. I was thinking of cloning the reader and passing the clone to the Datatable. Is this possible or advisable?

Is there a better way of finding the number of rows in my data reader? I know I could do something with a list (not fully sure what) but my datareader contains 33 fields of varying data types and I dont know how to put that all into a list.

thanks

Gavin
  • 437
  • 2
  • 8
  • 20
  • No it is just a one off query. The project is really small. The query is a basic SELECT tablexxx FROM WHERE. Can i use the SET NOCOUNT ON on this? SQL isnt really my thing. – Gavin Jun 09 '16 at 13:17
  • You could just use your DataTable now that it is full. – Crowcoder Jun 09 '16 at 13:17
  • 2
    Once you have loaded the DataTable with the reader you don't need anymore the reader. Just use the DataTable Rows, all data is there. – Steve Jun 09 '16 at 13:18
  • If I am using the following to run through my datareader how would I change this to be the datatable. while (reader.Read() && (i != noOfRows)) In other words how do i loop a datatable? – Gavin Jun 09 '16 at 13:22
  • Ill do it as foreach loop – Gavin Jun 09 '16 at 13:26
  • You could loop through table using `foreach(DataRow drow in DataTable.Rows) {}` – Hari Prasad Jun 09 '16 at 13:34
  • I used the DataTable and looped through it. All seems to be good. Thanks guys. – Gavin Jun 09 '16 at 14:13

1 Answers1

0

Neither ADO.NET nor SQL Server itself knows the number of rows before they have been sent. You can only find out by enumerating all rows.

Maybe you can just use a List instead of an array so that you don't have to pre-define the size?

usr
  • 168,620
  • 35
  • 240
  • 369