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

7
  • 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. Commented Jun 9, 2016 at 13:17
  • You could just use your DataTable now that it is full. Commented Jun 9, 2016 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. Commented Jun 9, 2016 at 13:18
  • If I am using the following to run through my datareader how would I change this to be the datatable. <code> while (reader.Read() && (i != noOfRows)) </code> In other words how do i loop a datatable? Commented Jun 9, 2016 at 13:22
  • Ill do it as foreach loop Commented Jun 9, 2016 at 13:26

1 Answer 1

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?

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.