Paging and Sorting of Grid View
This article gives a small example of using Gridview implementing paging and sorting using Asp.Net 2.0 . it is helpful for new learner
Gridview Paging and Sorting
Gridview control Displays the values of a data source in a table where each column represents a field and each row represents a record.
Check the sample code below
AllowPaging:
Gets or sets a value indicating whether the paging feature is enabled. AllowSorting:
Gets or sets a value indicating whether the sorting feature is enabled.
In aspx code please write the gridview as
<asp:GridView
AllowPaging=true
AllowSorting=true
ID="grdView"
runat="server"
AutoGenerateColumns=false
Width="50%"
GridLines="Horizontal"
PageSize =5
OnPageIndexChanging="grdView_PageIndexChanging"
OnSorting ="grdView_OnSorting"
DataKeyNames="CustomerName" HeaderStyle-ForeColor=green HeaderStyle-BackColor=RosyBrown
>
<RowStyle Backcolor="#e1e1ff" />
<Columns>
<asp:TemplateField HeaderText="First Name" SortExpression="CustomerName" HeaderStyle-ForeColor=Green>
<ItemTemplate>
<asp:Label ID="lblFirstName" Text='<%# DataBinder.Eval(Container.DataItem, "CustomerName")%>' runat="server" />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="City" SortExpression="City" HeaderStyle-Font-Underline=true HeaderStyle-ForeColor=white>
<ItemTemplate>
<asp:Label ID="lblCity" Text='<%# DataBinder.Eval(Container.DataItem, "City") %>' runat="server"></asp:Label>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>In Code Behind using the following code......
public partial class GridViewPgSort : System.Web.UI.Page
{
DataSet ds = new DataSet();
DataView dv = new DataView();
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
dv = bindgrid();
grdView.DataSource = dv;
grdView.DataBind();
}
}
private DataView bindgrid()
{
String ConnString = "Data Source=localhost;Initial Catalog=DatabaseName;Integrated Security=True";
String StrQuery = "select * from TableName";
SqlDataAdapter sadp = new SqlDataAdapter(StrQuery, ConnString);
sadp.Fill(ds);
if (ViewState["sortExpr"] != null)
{
dv = new DataView(ds.Tables[0]);
dv.Sort = (string)ViewState["sortExpr"];
}
else
dv = ds.Tables[0].DefaultView;
return dv;
}//Sorting Event:
protected void grdView_OnSorting (Object sender, GridViewSortEventArgs e)
{
ViewState["sortExpr"] = e.SortExpression;
grdView.DataSource = bindgrid();
grdView.DataBind();
}
<H2>// Paging Event
</H2>
protected void grdView_PageIndexChanging(Object sender, GridViewPageEventArgs e)
{
grdView.PageIndex = e.NewPageIndex;
grdView.DataSource = bindgrid();
grdView.DataBind();
}
}
Paging is working fine. Sorting is not working for me.