Sunday, May 16, 2010

How to: Displaying SharePoint List Data by using the SPGridView Control in SharePoint 2007

Hi all,

In my one of the blog posts, I had demonstrated a simple SPGridView which hosts in SharePoint 2007.  Its possible to bind the SharePoint list data onto the SPGridView which has similar SharePoint look and feel. Some other functions  such as pagination, sorting, filtering, groups etc are possible as well. Lets dive into this simple walk-through. I will extend the same "CustomAppPageGrid" project.

Step1: Open the "CustomAppPageGrid" project >> On "LAYOUTS" folder, right click >> Add >> New Item >> Choose "Web Form" >> Name: AppPage2.aspx

Step2: Copy all the elements of AppPage.aspx to AppPage2.aspx. It should look this:

AppPage2.aspx
--------------------------------------------------------------------------------------

<%@ Page Language="C#" MasterPageFile="~/_layouts/application.master" AutoEventWireup="true" Inherits="CustomAppPage.AppPage2, CustomAppPage,  Version=1.0.0.0, Culture=neutral, PublicKeyToken=fe057018f74cd3a4" %>

<%@ Register Tagprefix="SharePoint" Namespace="Microsoft.SharePoint.WebControls" Assembly="Microsoft.SharePoint, Version=12.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %>
<%@ Import Namespace="Microsoft.SharePoint" %>

<%--Control Place Holder--%>
<asp:Content ID="PageTitle" runat="server" contentplaceholderid="PlaceHolderPageTitle" >
   Customer Page Title
</asp:Content>

<asp:Content ID="PageTitleInTitleArea" runat="server"
             contentplaceholderid="PlaceHolderPageTitleInTitleArea" >
   Customer Title Area
</asp:Content>

<asp:Content ID="Main" runat="server" ContentPlaceHolderID="PlaceHolderMain">
    Custom SPGridView2
   
   <SharePoint:SPGridView
   runat="server"
   ID="GridView1"
   AutoGenerateColumns="false"
   RowStyle-BackColor="#DDDDDD"  />
  
</asp:Content>

--------------------------------------------------------------------------------------------------

AppPage2.aspx.cs
---------------------------------------------------------------------------------------------------


using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;

namespace CustomAppPage
{
     public partial class AppPage2 : Page
    {
       
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                #region 1. Creating new fields (columns) to the Grid

                //Creating new fields (columns) to the Grid
                SPGridViewHelper.AddField("Name", "Name", GridView1);
                SPGridViewHelper.AddField("Type", "Type", GridView1);

                #endregion

            }
        }

        protected override void CreateChildControls()
        {
            base.CreateChildControls();

            #region 2. Binds the SharePoint list to the Grid

            SPSite site = new SPSite("http://localhost/sites/Demo/");
            SPWeb web = site.OpenWeb();

            SPList list = web.Lists["Shared Documents"];

            SPGridViewHelper.BindListToGrid(site, list, GridView1);

            #endregion

        }

    }
}

---------------------------------------------------------------------------------------------------


This example, we are inheriting from PAGE class.


Step3: Under Utility folder, we create a new Helper class which will facilitate us to create and we call it SPGridViewHelper2.cs

The code for this helper class will illustrated below:
SPGridViewHelper2.cs
------------------------------------------------------------------------------
using System.Data;
using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;
using System.Web.UI.WebControls;


namespace CustomAppPage
{
    public class SPGridViewHelper
    {

        /// <summary>
        /// Creates a new column in the SPGridView
        /// </summary>
        /// <param name="dataField">The data field</param>
        /// <param name="headerText">The header text</param>
        /// <param name="grid">The Grid</param>
        public static void AddField(string dataField, string headerText, SPGridView grid)
        {
            BoundField columnName = new BoundField();
            columnName.DataField = dataField;
            columnName.HeaderText = headerText;

            grid.Columns.Add(columnName);

        }


        /// <summary>
        /// Binds the list the SPGridView
        /// </summary>
        /// <param name="spSite">The SPSite</param>
        /// <param name="spList">The SPList</param>
        /// <param name="grid">The grid</param>
        public static void BindListToGrid(SPSite spSite, SPList spList, SPGridView grid)
        {
            using(SPSite site = spSite)
            {
                using (SPWeb web = site.OpenWeb())
                {
                    SPList list = spList;
                    SPDataSource dataSource = new SPDataSource();
                    dataSource.List = list;

                    grid.DataSource = dataSource;
                    grid.DataBind();
                }
            }
        }

    }
}

------------------------------------------------------------------------------
Lets look at the functions below:

AddField(string dataField, string headerText, SPGridView grid):
This helper function take two string parameters and the SPGridView as parameter. When we are creating columns in the Grid, we have to supply two parameters named DataField and HeaderText. We can leverage the Utility class to create these columns and pass in the SPGridView as an additional parameter.

BindListToGrid(SPSite spSite, SPList spList, SPGridView grid): 
This function take three parameter: SPSite, SPList, SPGridView.For bind this SharePoint list, we need to pass in the site, and the list which we want to attach to the grid. We then create an instance of SPDataSource which will be the data source for the grid and eventually bind to the list. 

Deploy and test the solution



Step4: The Pagination

We can also do some kind of pagination of our grid. SPGridView comes different events such as PageIndexChanging, Sorting etc. through which we can give end users a better visual appeal. Lets create another application page named "AppPage3.aspx" page. 

AppPage3.aspx
------------------------------------------------------------------------------------------------
<%@ Page Language="C#" MasterPageFile="~/_layouts/application.master" AutoEventWireup="true" Inherits="CustomAppPage.AppPage3, CustomAppPage,  Version=1.0.0.0, Culture=neutral, PublicKeyToken=fe057018f74cd3a4" %>

<%@ Register Tagprefix="SharePoint" Namespace="Microsoft.SharePoint.WebControls" Assembly="Microsoft.SharePoint, Version=12.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %>
<%@ Import Namespace="Microsoft.SharePoint" %>

<%--Control Place Holder--%>
<asp:Content ID="PageTitle" runat="server" contentplaceholderid="PlaceHolderPageTitle" >
   Customer Page Title
</asp:Content>

<asp:Content ID="PageTitleInTitleArea" runat="server"
             contentplaceholderid="PlaceHolderPageTitleInTitleArea" >
   Customer Title Area
</asp:Content>

<asp:Content ID="Main" runat="server" ContentPlaceHolderID="PlaceHolderMain">
    Custom SPGridView3
   
   <SharePoint:SPGridView
   runat="server"
   ID="GridView1"
   AutoGenerateColumns="false"
   RowStyle-BackColor="#DDDDDD"  />
  
</asp:Content>

------------------------------------------------------------------------------------------------

 AppPage3.aspx.cs
------------------------------------------------------------------------------------------------
using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;

namespace CustomAppPage
{
    public partial class AppPage3 : System.Web.UI.Page
    {
        private DataView dv;

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {

                #region 1. Creating new fields (columns) to the Grid

                //Creating new fields (columns) to the Grid
                SPGridViewHelper.AddField("Name", "Name", GridView1);
                SPGridViewHelper.AddField("Type", "Type", GridView1);                #endregion

              
            }
        }

        protected override void CreateChildControls()
        {
            base.CreateChildControls();

            #region 2. Binds the SharePoint list to the Grid

            SPSite site = new SPSite("http://localhost/sites/Demo/");
            SPWeb web = site.OpenWeb();
            SPList list = web.Lists["Shared Documents"];
           
            DataTable dt = list.Items.GetDataTable();
            dv = new DataView(dt);

            SPGridViewHelper.BindListToGrid(site, list, GridView1);

            #endregion

            #region 3. Paging 

            //Paging
            GridView1.PageSize = 5;
            GridView1.AllowPaging = true;
            GridView1.PageIndexChanging += new GridViewPageEventHandler(GridView1_PageIndexChanging);
            GridView1.PagerTemplate = null;

            GridView1.DataBind();
            #endregion

            #region 4. Sorting
            //Sorting

            GridView1.AllowSorting = true;
            GridView1.Sorting += new GridViewSortEventHandler(GridView1_Sorting);
            #endregion


        }

        void GridView1_Sorting(object sender, GridViewSortEventArgs e)
        {
            var sortDirection = SortDirection.Ascending;

            string lastExpression = "";
            if (ViewState["SortExpression"] != null)
                lastExpression = ViewState["SortExpression"].ToString();

            string lastDirection = "asc";
            if (ViewState["SortDirection"] != null)
                lastDirection = ViewState["SortDirection"].ToString();

            string newDirection = "asc";
            if (e.SortExpression == lastExpression)
                newDirection = (lastDirection == "asc") ? "desc" : "asc";

            ViewState["SortExpression"] = e.SortExpression;
            ViewState["SortDirection"] = newDirection;

            if (newDirection == "asc")
            {
                sortDirection = SortDirection.Ascending;
            }
            else
            {
                sortDirection = SortDirection.Descending;
            }

            dv.Sort = e.SortExpression + " " + newDirection;
            GridView1.DataBind();

        }

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


------------------------------------------------------------------------------------------------

The events Paging and Sorting events are very similar as GridView in ASP.NET. Deploy and test

Cheers,
--aaroh

Download the source here.

References:

Bind the List with SPGridView
http://sharethispoint.com/archive/2006/09/05/UsingtheSharePointv3DataGridControlSPGridView.aspx
Filtering with SPGridView
http://vspug.com/bobsbonanza/2007/07/02/filtering-with-spgridview/

Paging

SharePoint list bind to SPGridView

SPGridView and SPMenuField  
 

No comments:

How to display Sharegate administrative dynamic reports via Power BI on SharePoint Online

After working in the SharePoint domain for a couple of years as SharePoint consultant , I am fortunate enough to help customers from man...