-->

Friday, September 11, 2015

Retrieving Data Using a DataReader in ASP.NET C#

Retrieving Data Using a DataReader in ASP.NET C#

Introduction
In this article i will show you, how to retrieve data from database table using DataReader. I will give a example of data fetching from database table using SqlDataReader class, also bind the GridView with the DataReader.
SqlDataReader 
Provides a way of reading a forward-only stream of rows from a SQL Server database ( source from msdn.microsoft.com)

Example How to bind gridview using SqlDataReader class

Step-1 : Take a Gridview onto design window. 
Step-2 :  Develop code for binding gridview using SqlDataReader.

using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data.SqlClient;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class datareadercl : System.Web.UI.Page
{
    SqlDataReader rd;
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack)
        {
            using (SqlConnection con = new SqlConnection())
            {
                con.ConnectionString =ConfigurationManager.ConnectionStrings ["ConnectionString"].ToString ();
                con.Open ();
                using(SqlCommand cmd=new SqlCommand ())
{
                    cmd.CommandText ="select * from [Table]";
                    cmd.Connection =con;
                    rd=cmd.ExecuteReader();
                    GridView1 .DataSource =rd;
                    GridView1 .DataBind ();                  
 
}

            }
        }
    }
}

OutPut of the program


bindgridview
Read() method of SqlDataReader class  : read next record


Read other related articles

Also read other articles

© Copyright 2013 Computer Programming | All Right Reserved