Powered by Blogger.

Friday, February 14, 2014

Bind gridview using datareader in asp.net



In this post we will discuss how to bind gridview using data reader in asp.net.

You can also check my previous posts on Difference between data reader and dataset in asp.net, Working with enterprise library for data access in asp.net Part-3 and Like operator examples in SQL Server 2008.

Below is the full code to bind gridview from Asp.Net. Here we have used stored procedure to retrieve data from the database:

Stored Procedure:

CREATE PROCEDURE Select_Employees

AS
BEGIN
Select * from Employees
END
GO

HTML Code:

<asp:GridView ID="GridView1" runat="server" >

    </asp:GridView>

.cs code:

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

public partial class _Default : System.Web.UI.Page
{
    string conn = "Data Source=localhost;database=sample;Integrated Security=true";
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            bindGridview();
        }
    }

    private void bindGridview()
    {
        SqlConnection con = new SqlConnection(conn);
        SqlCommand cmd = new SqlCommand("Select_Employees", con);
        cmd.CommandType = CommandType.StoredProcedure;
        SqlDataReader reader;
        try
        {
            con.Open();
            reader = cmd.ExecuteReader();
            GridView1.DataSource = reader;
            GridView1.DataBind();
            reader.Close();
        }
        catch (Exception ex)
        {

        }
        finally
        {
            con.Close();
        }
    }
}
But we can not implement paging in gridview with data reader.



0 comments

Post a Comment