ExecuteReader() in ADO.NET using asp.net with Example

In our previous article we have discussed ExecuteNonQuery() and ExecuteScalar() methods with examples. All three methods are part of SQL Command Class. You can visit ExecuteNonQuery() with Example in Asp.net and ExecuteScalar() with Example in Asp.net for more details. In this article we comes with ExecuteReader() with example code.
ExecuteReader()
ExecuteReader() method will return set of row on execution of SQL Statement.When SQLCommand SQLCommand.ExecuteReader() execute it will initialize SQLDataReader object.  SQLDataReader is forwardonly and readonly.

ExecuteReader() Example in Ado.net


Database Structure for our example

Column NameData Type
IDint(Primary Key)
First Namevarchar(50)
Last Namevarchar(50)
Cityvarchar(30)
EmailIDvarchar(100)

Sql Query
CREATE TABLE Sample(
 [ID] [int] IDENTITY(1,1) NOT NULL,
 [FirstName] [varchar](50) NULL,
 [LastName] [varchar](50) NULL,
 [City] [varchar](30) NULL,
 [EmailID] [varchar](100) NULL)
We have Pre-Inserted data in our table
ExecuteScalar() Example in asp.net

Default.aspx
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>ExecuteReader Example in Asp.net</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
     <asp:Button ID="btnFetch" runat="server" OnClick="btnFetch_Click" Text="Fetch Data" /><br />
        <asp:GridView ID="gvData" runat="server" CellPadding="4" ForeColor="#333333" GridLines="None">
            <AlternatingRowStyle BackColor="White" />       
            <HeaderStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
            <RowStyle BackColor="#EFF3FB" />
        </asp:GridView>
    </div>
    </form>
</body>
</html>
Default.aspx.cs
 protected void btnFetch_Click(object sender, EventArgs e)
    {
        string ConnectionString = "Enter your ConnectionString Here";
        using (SqlConnection con = new SqlConnection(ConnectionString))
        {
            try
            {
                con.Open();
                string Query = "select FirstName, LastName, City, EmailID from Sample";
                SqlCommand cmd = new SqlCommand(Query, con);
                SqlDataReader sdr = cmd.ExecuteReader();// use of ExecuteReader()
                gvData.DataSource = sdr;
                gvData.DataBind();
            }
            catch
            {
                Response.Write("Error Occur While Processing your Request");
            }
            finally
            {
                con.Close();
            }
        }
    }
Demo 
Download Sample Code