views:

207

answers:

3

I am a beginner.

I heard that DataReader works on forward only readonly fashion and at a time it will read a single record.Suppose when i execute the below code

SqlDataReader reader=cmd.ExecuteReader();
gv1.DataSource=reader;
gv.DataBind();

How the does the gridview populate all records?.As the reader is capable of reading one row per read,I thought only the last row is available for GridView to display.

A: 

BindData will read data from the reader, one record at a time, populating the GridView as it goes. The GridView does not maintain a connection to the server by way of the reader.

Michael Petrotta
A: 

Internally, the Read() method of the DataReader is called during DataBinding, until it returns false (indicating that there are no more records). As each record is fetched, it is added to the html to be rendered.

MikeB
A: 

According to MSDN:

The GridView control can be bound to a data source control (such as SqlDataSource, ObjectDataSource, and so on), as well as any data source that implements the System.Collections.IEnumerable interface (such as System.Data.DataView, System.Collections.ArrayList, or System.Collections.Hashtable). Use one of the following methods to bind the GridView control to the appropriate data source type:

As you can see you are just setting your SqlDataReader reference to GridView.DataSource. When you call GridView.DataBind method, GridView reads it by while (reader.Read()) and fills the corresponding data.

JCasso