Advertisement
In this Article I will explain how to create Sorting and Pagination in SPGridView.
First create a empty solution,After
that select Visualwebpart.
In ASCX page write the following code.
<SharePoint:SPGridView
ID="spgrid"
runat="server"
AllowPaging="true"
PageSize="2"
AutoGenerateColumns="false"
EnableViewState
="false"
AllowSorting="true"
OnPageIndexChanging="PageIndexChanging"
>
<PagerStyle
HorizontalAlign="Right"
/>
<RowStyle
HorizontalAlign="Left"></RowStyle>
<Columns>
<asp:TemplateField
HeaderText="Incident
ID">
<ItemTemplate>
<asp:Label
ID="lblSRNO"
runat="server"
Text='<%#Container.DataItemIndex+1
%>'>
</asp:Label>
</ItemTemplate>
</asp:TemplateField>
<SharePoint:SPBoundField
DataField="IncidentName"
SortExpression
=
"IncidentName"
HeaderText="IncidentName"
/>
<SharePoint:SPBoundField
DataField="IncidentRisk"
SortExpression="IncidentRisk"
HeaderText="PotentialRisk"
/>
<SharePoint:SPBoundField
DataField="IncidentDate"
SortExpression="IncidentDate"
HeaderText="ReportedDate"
/>
</Columns>
<EmptyDataTemplate>
No
Data Found
</EmptyDataTemplate>
</SharePoint:SPGridView>
In ascx.cs write the following code.
protected
void
Page_Load(object
sender, EventArgs
e)
{
try
{
if
(!IsPostBack)
{
ddlLoadCatFilter();
Getdata();
}
}
catch
(Exception
ex)
{
throw
ex;
}
}
public
void
Getdata()
{
SPWeb
currentWeb = SPContext.Current.Web;
SPList
lst = currentWeb.Lists["IncidentManagementList"];
SPListItemCollection
myColl = lst.Items;
if
(myColl.Count > 0)
{
spgrid.DataSource
= myColl.GetDataTable();
spgrid.DataBind();
}
}
protected
void
PageIndexChanging(object
sender, GridViewPageEventArgs
e)
{
spgrid.PageIndex
= e.NewPageIndex;
Getdata();
}
protected
void
spgrid_Sorting(object
sender, GridViewSortEventArgs
e)
{
string
sortExpression = e.SortExpression;
if
(GridViewSortDirection == SortDirection.Ascending)
{
GridViewSortDirection
= SortDirection.Descending;
SortGridView(sortExpression,
DESCENDING);
}
else
{
GridViewSortDirection
= SortDirection.Ascending;
SortGridView(sortExpression,
ASCENDING);
}
}
private
void
SortGridView(string
sortExpression, string
direction)
{
Getdata();
DataTable
dt = spgrid.DataSource as
DataTable;
DataView
dv = new
DataView(dt);
dv.Sort
= sortExpression + direction;
spgrid.DataSource
= dv;
spgrid.DataBind();
}
private
const
string
ASCENDING = "
ASC";
private
const
string
DESCENDING = "
DESC";
public
SortDirection
GridViewSortDirection
{
get
{
if
(ViewState["sortDirection"]
== null)
ViewState["sortDirection"]
= SortDirection.Ascending;
return
(SortDirection)ViewState["sortDirection"];
}
set
{
ViewState["sortDirection"]
= value;
}
}
where is ddlLoadCatFilter() function.
ReplyDelete