Follow by Email

Thursday, June 13, 2013

ADO.net | binding gridview using sqldatareader in asp.net(C#) | sqldatareader example in asp.net

hi in this post i will show how to bind a GridView using SqlDataReader in asp.net.

SqlDataReader read the records from the database on a row by row basis, which means as soon as a single record is fetched from the database it is returned Whereas in case of SqlDataAdapter the whole set of records are fetched and then returned. Thus SqlDataReader is a good choice if we have large amount of data to be shown in a grid.

Below is the code to bind grid view using SqlDataReader :

 void GetData()
    {
        string conStr = ConfigurationManager.ConnectionStrings["NORTHWNDConnectionString"].ConnectionString.ToString();
        SqlConnection s1 = new SqlConnection(conStr);
        s1.Open();

        SqlCommand cmd = new SqlCommand();
        cmd.Connection = s1;
        cmd.CommandType = CommandType.Text;
        cmd.CommandText = "select * from company";
        SqlDataReader reader = cmd.ExecuteReader();
        GridView1.DataSource = reader;
        GridView1.DataBind();

        s1.Close();
    }