Bind gridview using datareader in asp.net

InfoPath alternatives for form designing SharePoint

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.

Similar SharePoint 2013 Tutorials


About Bijay Kumar

I am Bijay from Odisha, India. Currently working in my own venture TSInfo Technologies in Bangalore, India. I am Microsoft Office Servers and Services (SharePoint) MVP (5 times). I works in SharePoint 2016/2013/2010, SharePoint Online Office 365 etc. Check out My MVP Profile.. I also run popular SharePoint web site SharePointSky.com

View all posts by Bijay Kumar →

Leave a Reply