Using Sharepoint GridView

Spread the love

One of the most common scenarios faced by SharePoint Developers while creating custom Webparts or Application pages is to create a Gridview providing Sorting, Filtering, look n feel etc that is similar to a SharePoint list.
In this blog I would demonstrate with a simple example how we use SPGridView in our solution.

Following is the declaration of SPgridView in the aspx/ascx page:

<SharePoint:SPGridView ID="gvICSSDocuments" runat="server" AutoGenerateColumns="false" Width="850px">
                <RowStyle BackColor="#D0D8E8" Height="30px" HorizontalAlign="Left"/>
                <AlternatingRowStyle BackColor="#E9EDF4" Height="30px" HorizontalAlign="Left"/>
                <HeaderStyle HorizontalAlign="Left" CssClass="ms-viewheadertr" />
                <asp:TemplateField HeaderText="Year" ControlStyle-Width="100px" SortExpression="Year" HeaderStyle-CssClass="ms-viewheadertr">
                        <asp:Label ID="lblCreated" runat="server" Text='<%# Eval("Year") %>'></asp:Label>
                <asp:TemplateField HeaderText="Title" ControlStyle-Width="250px" SortExpression="Title" HeaderStyle-CssClass="ms-viewheadertr">
                        <asp:Label ID="lblTitle" runat="server" Text='<%# Eval("Title") %>'></asp:Label>
                <asp:TemplateField HeaderText="Description" ControlStyle-Width="300px" HeaderStyle-HorizontalAlign="Left"  HeaderStyle-CssClass="ms-viewheadertr">
                        <asp:Label ID="lblDescription" runat="server" Text='<%# Eval("Description") %>'></asp:Label>
                <asp:TemplateField HeaderText="Attachment" ControlStyle-Width="200px" SortExpression="Name" HeaderStyle-CssClass="ms-viewheadertr">
                        <asp:HyperLink ID="hlnkDocument" runat="server" Text='<%# Eval("Name") %>' NavigateUrl='<%# Eval("Url") %>'
                <asp:Label ID="lblNoAccess" Text="No documents available" runat="server" CssClass="emptyDataLabel"></asp:Label>


All the event binding information has to be provided in the code and we cannot provide then declaratively in the aspx/ascx page for SPGridview. Doing so throws runtime exception.

Let us now see how we tag events, bind and work with the Grid view in the code behind:

In the Page_Load event we are declaring the GridView Object, its event and Datasource.
SPgridView uses ObjectDataSource hence we need to create Instance of ObjectDatasource, specify its select,update,delete methods as required.

public wbDocumentViewer PropertyObj { get; set; }
ObjectDataSource gridDS = null;
        protected void Page_Load(object sender, EventArgs e)
                docLibrary = PropertyObj.DocLibrary;
                managerGroup = PropertyObj.ManagerGroup;
                viewerGroup = PropertyObj.ViewerGroup;
                manageDocPageURL = PropertyObj.ManageDocumentPageURL;
                const string DATASOURCEID = "gridDS";
                gridDS = new ObjectDataSource();
                gridDS.ID = DATASOURCEID;
                gridDS.SelectMethod = "SelectData";
                gridDS.TypeName = this.GetType().AssemblyQualifiedName;
                gridDS.ObjectCreating += new ObjectDataSourceObjectEventHandler(gridDS_ObjectCreating);
            catch (Exception ex)
                SPDiagnosticsService diagnosticsService = SPDiagnosticsService.Local;
                SPDiagnosticsCategory cat = diagnosticsService.Areas["SharePoint Foundation"].Categories["Unknown"];
                diagnosticsService.WriteTrace(1, cat, TraceSeverity.Medium, ex.StackTrace, cat.Name, cat.Area.Name);               
                SPUtility.TransferToErrorPage("Some Error occured, Please try after some time. <br/> If problem persists, contact your adminstrator");

Let us look at the BindDocuments Method for Binding the objectDataSource to GridView. Notice that the Sorting,PageIndexChanging etc method are event tagged for the SPgridView but for Filtering we tag ObjectDataSource’s Filter event.

private void BindDocuments()
            gvICSSDocuments.AllowPaging = true;
            // Sorting
            gvICSSDocuments.AllowSorting = true;
            //allow Filtering
            gvICSSDocuments.FilterDataFields = "Year,Title,,Name";
            gvICSSDocuments.FilteredDataSourcePropertyName = "FilterExpression";
            gvICSSDocuments.FilteredDataSourcePropertyFormat = "{1} = '{0}'";
            gvICSSDocuments.Sorting += new GridViewSortEventHandler(gvDocuments_Sorting);
            gvICSSDocuments.PageIndexChanging += new GridViewPageEventHandler(gvDocuments_PageIndexChanging);
            //For Filtering
            gridDS.Filtering += new ObjectDataSourceFilteringEventHandler(gridDS_Filtering);
            gvICSSDocuments.AutoGenerateColumns = false;
            gvICSSDocuments.AllowFiltering = true;
            gvICSSDocuments.PagerTemplate = null;
            gvICSSDocuments.PageSize = 10;
            gvICSSDocuments.DataSourceID = gridDS.ID;

Also Note that in the FilterDataFields Property for the Gridview we are providing comma separated list of columns.
It should be in order of columns as added in the GridView Declaration. Also Note that there are two commas after Title column (Year,Title,,Name).
This is to done for columns on whom we don’t want filtering. Like In our example we have skipped filtering on the description column.
Note that the order of columns provided for filtering should be same as the order of coulns specified in gridview declaration.
Else the filter values of one column will show on clicking filter options of another column.

Let us see now the Select method for the ObjectDataSource. Note that the SelectData Method creates a DataTable from the data fetched from SharePoint Doc Library and returns the DataTable.

public DataTable SelectData()
            DataTable dataSource = new DataTable();
                SPSite site = SPContext.Current.Web.Site;
                SPWeb web = site.OpenWeb();
                SPList lstICSSDocuments = web.Lists[docLibrary];
                SPQuery query = new SPQuery();
                IEnumerable<SPListItem> lstItemICSSDocuments = lstICSSDocuments.GetItems(query).OfType<SPListItem>();
                    //SPGroup grpName = web.Groups["ICSSViewers"];
                      var committeeAndGroupDocumentswithURL = lstItemICSSDocuments.Select(x => new { Year = x["Year"], Description = x["Description"], Name = x["Name"], Title = x["Title"], Url = site.Url + "/" + x.Url });
                        foreach (var document in committeeAndGroupDocumentswithURL)
                            DataRow dr = dataSource.NewRow();
                            dr["Title"] = document.Title;
                            dr["Url"] = document.Url;
                            dr["Name"] = document.Name;
                            dr["Description"] = document.Description;
                            dr["Year"] = document.Year;
            catch (Exception ex)
                SPDiagnosticsService diagnosticsService = SPDiagnosticsService.Local;
                SPDiagnosticsCategory cat = diagnosticsService.Areas["SharePoint Foundation"].Categories["Unknown"];
                diagnosticsService.WriteTrace(1, cat, TraceSeverity.Medium, ex.StackTrace, cat.Name, cat.Area.Name);
                SPUtility.TransferToErrorPage("Some Error occured, Please try after some time. <br/> If problem persists, contact your adminstrator");
            return dataSource;

The Sorting, Filtering, PageChanging etc are all handled similar to normal gridviews. 
One could always implement RowBound, RowUpdating,RowEditing, RowDeleting etc events of the gridview exactly similar to gridviews.
However, You may need to provide blank method implementations for ObjectDataSource update and Delete methods in case of Updating/Deleting from the gridview.

void gridDS_ObjectCreating(object sender, ObjectDataSourceEventArgs e)
            e.ObjectInstance = this;
        void gvDocuments_Sorting(object sender, GridViewSortEventArgs e)
            string lastExpression = "";
            if (ViewState["SortExpression"] != null)
                lastExpression = ViewState["SortExpression"].ToString();
            string lastDirection = "asc";
            if (ViewState["SortDirection"] != null)
                lastDirection = ViewState["SortDirection"].ToString();
            string newDirection = string.Empty;
            if (e.SortExpression == lastExpression)
                e.SortDirection = (lastDirection == "asc") ? System.Web.UI.WebControls.SortDirection.Descending : System.Web.UI.WebControls.SortDirection.Ascending;
            newDirection = (e.SortDirection == System.Web.UI.WebControls.SortDirection.Descending) ? "desc" : "asc";
            ViewState["SortExpression"] = e.SortExpression;
            ViewState["SortDirection"] = newDirection;
            //For Filter
            if (ViewState["FilterExpression"] != null)
                gridDS.FilterExpression = (string)ViewState["FilterExpression"];
  void gvDocuments_PageIndexChanging(object sender, GridViewPageEventArgs e)
            gvICSSDocuments.PageIndex = e.NewPageIndex;
            gvICSSDocuments.DataSourceID = gridDS.ID;
        //For Filtering
        private void gridDS_Filtering(object sender, ObjectDataSourceFilteringEventArgs e)
            ViewState["FilterExpression"] = ((ObjectDataSourceView)sender).FilterExpression;
        protected sealed override void LoadViewState(object savedState)
            if (Context.Request.Form["__EVENTARGUMENT"] != null &&
                // Clear FilterExpression

Happy Coding!!

Leave a Reply

Your email address will not be published. Required fields are marked *

  • Broadband Speed Check
    Spread the love Broadband speed refers to the data transfer rate from the internet to your computer.  Broadband speed tests measure […]
  • Compare Internet Service Providers (DSL)
    Spread the love   Verizon DSL Qwest DSL Deluxe AT&T U-Verse High Speed Internet. Maximum connection speed (Download / Upload)* 0.5 -1 […]
  • Compare High Speed 56K Dialup ISP
    Spread the love   PeoplePC AT&T EarthLink AOL Time usage/m Unlimited Unlimited 200 hr Unlimited Unlimited Unlimited […]
  • DSL vs Cable Internet – Differences between DSL and Cable Internet
    Spread the love DSL internet Cable internet Data transmission via phone line Data transmission via coaxial cable line Connected through DSL modem […]
  • VoIP – Bonus Features
    Spread the love Unlike landline phone service, VoIP providers often provide many bonus features for free.  Some of them are very useful to […]
  • Virtual Telephone Number – What is a virtual telephone number?
    Spread the love A virtual telephone number is simply a phone number that doesn’t have a directly-associated phone line.  It is a vanity number […]
  • Satellite VoIP
    Spread the love The market of VoIP has been expanding rapidly over the past few years.  VoIP allows the transmission of voice signals over the […]
  • VoIP – FAQ
    Spread the love VoIP is a relatively new phone service to many consumers.  Some of you may have hesitations when transferring your phone service from […]
  • Cable Internet Service Providers
    Spread the love Comcast Cable Internet Maximum connection speed: 8 Mbps / 384 kbps (download speed up to 100 times faster than 56K dialup) $75 Cash […]
  • Broadband DSL. What does DSL stand for?
    Spread the love DSL stands for “Digital Subscriber Line”. It is a family of technologies that provides digital data transmission over the wires of […]
  • Broadband Internet
    Spread the love Broadband Internet, also called High Speed Internet, is an internet connection offering high data transmission rate of 256 Kbps […]
  • Wireless Internet Service Providers
    Spread the love AT&T Wi-Fi service can connect you with public wireless high speed internet access at speeds much faster than dialup when you are […]
  • Satellite Internet Providers
    Spread the love HughesNetTM offers affordable, super-fast, always-on, satellite Internet access and is available anywhere in the contiguous […]
  • VoIP for Small Business
    Spread the love VoIP, or voice over internet protocol, is a technology that has revolutionized the way businesses communicate today. This technology […]
  • Wireless Internet / Wi-Fi
    Spread the love How does wireless internet work?  Wireless internet transfers digital data using radio frequency. Wi-Fi is the leading wireless […]
  • Ten Tips for Choosing a VoIP Provider
    Spread the love What should you consider when choosing a VoIP provider? Read our simple tips and do your own VoIP comparisons before making your […]
  • Satellite Internet
    Spread the love Satellite Internet Access is probably the most expensive high speed internet service for home users. However, in rural or remote […]
  • Best VoIP Providers
    Spread the love VoIPo Residential VoIP Key Features: Unlimited Calls to US/Canada Over 38 Calling Features 2nd Line (Cloned) Free Equipment Free […]
  • ISP: Tips for Choosing a Good Broadband ISP
    Spread the love For those who are relocating or moving from dialup to broadband internet access, choosing a broadband ISP can cause some headaches. […]
  • 56K Dialup ISP / High Speed Dialup ISP
    Spread the love PeoplePC Accelerated Unlimited internet access Accelerated technology increases speed by up to 5X Smart dialer technology (dial the […]