Load IDataReader/DataReader Into DataTable and Bind to GridView

Posted: September 28, 2011 in ASP.Net

To bind data to a GridView using IDataReader/DataReader with a DataTable, you can do the following:

try
{
  Microsoft.Practices.EnterpriseLibrary.Data.Sql.SqlDatabase DAL = new Microsoft.Practices.EnterpriseLibrary.Data.Sql.SqlDatabase(MyConnectionString);
  System.Data.Common.DbCommand dbgCommand = DAL.GetStoredProcCommand("MyStoredProcedure");
  IDataReader rdr = DAL.ExecuteReader(dbgCommand);
  try
  {
    DataTable dt = new DataTable();
    dt.Load(rdr);
    if (dt.Rows.Count != 0)
    {
      MyGridView.DataSource = dt;
      MyGridView.DataBind();
    }
    else
    {
      ...
    }
  }
  finally
  {
    rdr.Close();
    rdr.Dispose();
  }
}
catch (Exception ex)
{
  ...
}
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s