DataReader is the best option when all you want to do is to iterate through the database and display the results. Most of the time we are not closing the datareader object. And even if we close it than we do it the wrong time and an error message is displayed saying that the datareader cannot proceed because its closed.
DataReader is an object which means its a reference type variable so you can close it from the calling code:
Here is a example:
GetAllTasks Method: I am using Enterprise Library Data Access Block. IDataReader is an interface which lets you access any datasource.
public IDataReader GetAllTasks()
{
Database db = DatabaseFactory.CreateDatabase();
DBCommandWrapper selectCommandWrapper = db.GetStoredProcCommandWrapper("GetAllTasks");
IDataReader dataReader = null;
try
{
dataReader = db.ExecuteReader(selectCommandWrapper);
return dataReader;
}
catch(Exception ex)
{
string exception = ex.Message;
return null;
}
}
The Calling Code:
if(!Page.IsPostBack)
{
Tasks tasks = new Tasks();
IDataReader reader = tasks.GetAllTasks();
myDataGrid.DataSource = reader;
myDataGrid.DataBind();
// Close the Reader
if(reader!=null)
{
reader.Close(); }
}
No comments:
Post a Comment