The DataReader object is a forward-only and read only object
- It is simple and fast compare to dataset.
- It provides connection oriented environment.
- It needs explicit open and close the connection.
- DataReader object provides the read() method for reading the records. read() method returns Boolean type.
- DataReader object cannot initialize directly, you must use ExecuteReader() method to initialize this object.
Example:
using System;
using System.Web.UI;
using System.Data;
using System.Data.SqlClient;
public partial class CareerRide : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
SqlDataReader reader;
SqlConnection MyConnection = new SqlConnection("Data Source=name of your datasource;Initial Catalog=Employee;Integrated Security=True");
SqlCommand cmd = new SqlCommand();
cmd.CommandText = "SELECT * FROM emp";
cmd.CommandType = CommandType.Text;
cmd.Connection = MyConnection; MyConnection.Open();
reader = cmd.ExecuteReader(CommandBehavior.CloseConnection);
GridView1.DataSource = reader;
GridView1.DataBind();
cmd.Dispose();
MyConnection.Dispose();
}
}
}