How to Implement manual Paging and Sorting in Gridview ?


Hi
In so many condition we have to do manual manual Paging and Sorting in Gridview without the sqldatasource control.

Here are some few steps do this task

1.Configure the Gridview like this

<asp:GridView ID=”GridView1″ runat=”server” AutoGenerateColumns=”False”
AllowSorting=”True” AllowPaging=”true” PageSize=”3″
onsorting=”GridView1_Sorting” onpageindexchanging=”GridView1_PageIndexChanging”>
<Columns>
<asp:TemplateField  SortExpression=”EmpId” HeaderText=”EmpNo”>
<ItemTemplate>
<asp:Label ID=”lblEmpId” runat=”server” Text='<%#Eval(“EmpId”) %>’ />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField SortExpression=”EmpName” HeaderText=”EmpName”>
<ItemTemplate>
<asp:Label ID=”lblEmpName” runat=”server” Text='<%#Eval(“EmpName”) %>’ />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>

2: Click on PageIndex Changing and Sorting event of gridview

3.Write the code like this in code behind file.

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

public partial class _Default : System.Web.UI.Page
{
SqlConnection con = new SqlConnection(“Data Source=Test-SERVER;Initial Catalog=Test;Integrated Security=True”);

protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
GridView1.DataSource = GetData();
GridView1.DataBind();
}

}

protected void GridView1_Sorting(object sender, GridViewSortEventArgs e)
{

DataTable dt = GetData();

DataView dv = dt.DefaultView;

if (ViewState[“tt”] ==null)
{
ViewState[“tt”] = “DESC”;

}
else
{
if (ViewState[“tt”].ToString() == “ASC”)
{
ViewState[“tt”] = “DESC”;
}
else
{
ViewState[“tt”] = “ASC”;
}
}
string tt = ViewState[“tt”].ToString();
dv.Sort = e.SortExpression + ” ” + tt;

GridView1.DataSource = dv;
GridView1.DataBind();

}

private DataTable GetData()
{
SqlCommand cmd = new SqlCommand(“Select *from tblEmp”, con);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
return dt;

}

protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
GridView1.PageIndex = e.NewPageIndex;
GridView1.DataSource = GetData();
GridView1.DataBind();

}
}

4: Then we will get output like this

Advertisement

4 thoughts on “How to Implement manual Paging and Sorting in Gridview ?

  1. Richard March 4, 2011 / 5:04 pm

    Thanks! Works like a charm!

  2. sri March 6, 2012 / 11:21 am

    Thanks dear. its working fine

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.