Search code examples
asp.netado.netidatareader

Does a IDataReader get automatically get closed when set as a datasource?


When you assign an active IDataReader object to either a Repeater, GridView, etc., does it automatically get closed upon completion of the DataBind method call or do we still need to explicitly close it ourselves?

this.sampleRepeater.DataSource = ExampleDAL.GetIDataReader();
this.sampleRepeater.DataBind();

Solution

  • With the DataReader type, the connection needs to remain open while you're accessing the data. This is not a disconnected data source like say, a DataTable. You must close this out yourself else you're waiting for it to die of natural causes:).

    Interested in alternatives? Put your data in to a DataTable, DataSet, or convert the returned rows in to a List of custom objects and return one of those.

    Hope that helps!