We
normally use asp.net gridview control as substitute to SharePoint gridview
Control. Compare to asp.net gridview control SharePoint gridview provides rich
functionality. Below two are the reasons that I feel to use SPGridView control
instead of asp.net gridview control.
1. SPGridView
is inherit from GridView, so it will have features of GridView and also
some special features that suite for SharePoint environment, so for a
SharePoint web part, I suggest to use SPGridView.
2. Also
SPGridview control supports built-in SharePoint cascading style
sheets, menus, sorting in SharePoint manner.
In
this blog I will try to show,
1. Create
SPGridView.
2. Bind
data source to SPGridView.
3. Apply
paging to SPGridView.
4. Allow
Filtering.
Let’s
create demo SPGridView.I
have created a list on my SharePoint site with following columns.
Column
Name
|
Type
|
ID
|
int
|
Title
|
Single
line of text
|
Email
|
Single line of text
|
Location
|
Single
line of text
|
1. Open Visual studio.
2. Create an empty sharepoint project.(Project Name : SPGridViewDemo)
3. Add a visual webpart to your project.(WebPart Name :
ShowDetails)
4. Now add following code to your webpart (ShowDetails.ascx)
<SharePoint:SPGridView ID="gvDemo" runat="server" AllowFiltering="true" AllowPaging="true" AllowSorting="true" AutoGenerateColumns="false" EnableTheming="true" FilterDataFields=",Title,Email,Location" FilteredDataSourcePropertyFormat="{1} like '{0}'" FilteredDataSourcePropertyName="FilterExpression" HeaderStyle-HorizontalAlign="Left" OnSorting="gvDemo_Sorting" PagerSettings-Position="Bottom" PageSize="3" ShowHeader="true">
<Columns>
<asp:BoundField DataField="ID" HeaderText="ID" ReadOnly="true" />
<asp:BoundField DataField="Title" HeaderText="Title" ReadOnly="true" />
<asp:BoundField DataField="Email" HeaderText="Email" ReadOnly="true" />
<asp:BoundField DataField="Location" HeaderText="Location" ReadOnly="true" />
</Columns>
</SharePoint:SPGridView>
You will need to
create gvDemo_Sorting() method in code behind. FilterDataFields contains
the order of fields that are to be allowed filtering. In case you don’t
want to apply filtering on any column then you can just leave that
position blank just as I did for first column(FilterDataFields=",Title,Email,Location").
5. Now
we need to add asp.net ObjectDataSource
that will bind data to gridview whenever required. We will add following code
below the </SharePoint:SPGridView> tag.
<asp:ObjectDataSource ID="gridds" runat="server" OnFiltering="gridds_Filtering" OnObjectCreating="gridds_ObjectCreating" SelectMethod="SelectGridData"></asp:ObjectDataSource>
In
the above two lines of code SelectMethod name will be the name of the method
that contains code to fetch data from SharePoint list. You will also need to
create object creating and filtering
handlers methods in code behind.
6. Finally
add SPGridViewPager that will allow us to apply paging to SPGridView. Add below
code below </asp:ObjectDataSource> tag.
<SharePoint:SPGridViewPager ID="spgvCVPager" runat="server" GridViewId="gvDemo"> </SharePoint:SPGridViewPager>
Now
let’s add methods to code behind file:
1. Add
below code to page load event. This will Assign type of current instance to ObjectDataSource control.
gridds.TypeName =
this.GetType().AssemblyQualifiedName;
gvDemo.DataSourceID = gridds.ID;
2. Add
following method to code behind. Method will check if any column value contains
any special character. If any wild card character is found it removes it.
public string
EscapeLikeValue(string valueWithoutWildcards)
{
StringBuilder sb = new StringBuilder();
for (int i = 0;
i < valueWithoutWildcards.Length; i++)
{
char c = valueWithoutWildcards[i];
if (c == '*' || c == '%' || c == '[' || c == ']')
sb.AppendFormat("[{0}]", c);
else if (c == '\'')
sb.Append("''");
else
sb.Append(c);
}
return
sb.ToString();
}
protected void gridds_ObjectCreating(object sender, ObjectDataSourceEventArgs e)
{
e.ObjectInstance = this;
}
protected void gridds_ObjectCreating(object sender, ObjectDataSourceEventArgs e)
{
e.ObjectInstance = this;
}
3. Customize methods as shown
below.
protected void
gvDemo_Sorting(object sender, GridViewSortEventArgs e)
{
if
(ViewState["FilterExpression"] != null)
{
gridds.FilterExpression = (string)ViewState["FilterExpression"];
}
}
public DataTable SelectGridData()
{
DataTable dtTemp = null;
using (SPSite site = new SPSite(SPContext.Current.Web.Url))
{
using (SPWeb web = site.OpenWeb())
{
SPList list = web.Lists.TryGetList("Test");
if (list != null)
{
dtTemp=
list.GetItems().GetDataTable();
}
}
return dtTemp;
}
}
protected sealed override void
LoadViewState(object savedState)
{
base.LoadViewState(savedState);
if
(Context.Request.Form["__EVENTARGUMENT"] != null && Context.Request.Form["__EVENTARGUMENT"].EndsWith("__ClearFilter__"))
{
// Clear FilterExpression
ViewState.Remove("FilterExpression");
}
}
protected override void
OnPreRender(EventArgs e)
{
if (!string.IsNullOrEmpty(gridds.FilterExpression))
{
gridds.FilterExpression = String.Format(gvDemo.FilteredDataSourcePropertyFormat,
EscapeLikeValue(gvDemo.FilterFieldValue), gvDemo.FilterFieldName);
}
base.OnPreRender(e);
}
protected void
gridds_Filtering(object sender, ObjectDataSourceFilteringEventArgs e)
{
ViewState["FilterExpression"] = ((ObjectDataSourceView)sender).FilterExpression;
}
In
above methods we are adding filter column to view state in gridds_Filtering()
method, We are loading the view state in LoadViewState() method, and fetching
data from SharePoint list in SelectGridData() method.
Now
just deploy the project. Add webpart to your site and you will see following
gridview.
Now
we can see that paging is applied to SPGridView also below images shows
filtering that are applied to SPGridView.
Regards,
Keyur
Pandya
Thanks a lot for this article! Very informative.
ReplyDelete