Skip to main content

SPGridView control Example

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;
        }
               
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

Comments

  1. Thanks a lot for this article! Very informative.

    ReplyDelete

Post a Comment

Popular posts from this blog

Business Data Connectivity

I came to a requirement wherein I was supposed to get data from an 3 rd party portal using API’s and then bring them to SharePoint server. The first approach that I finalized was just to make BDC solution that will get data from 3 rd party portal and will deploy it to SharePoint. How to Create BDC solution in SharePoint? I found below link that is having really great description about hot to create and deploy the BDC solution to SharePoint. http://www.c-sharpcorner.com/uploadfile/hung123/creating-business-data-connectivity-service-using-visual-studio-2010/ After creating an POC I came to know that BDC model cannot be deployed on Multi tenant farm. So what can be done next? After some amount of googling I came to know that we can create BDC solution using WCF services also. So I created a WCF service solution that acted as a wrapper that used to fetch data from the portal. We can them publish that service to IIS or Server and use the servic...

Identity client runtime library (IDCRL) did not get a response from the login server.

Recently I was doing some testing with a background PowerShell and encountered a weird error. “Identity client runtime library (IDCRL) did not get a response from the login server”. The error that you might encounter while working with PowerShell. This error is very misleading when it comes to identifying what could go wrong. After doing quite a good amount of research below are the probable causes for the error. Invalid Credentials MFA (Multi-Factor Authentication) Manage security defaults. Solutions Invalid Credentials Check if your credentials are wrong. Especially if you are using variables. MFA (Multi-Factor Authentication) Check if MFA is enabled on the account which you are using. These only affect you badly if you are developing PowerShell for a background Job. Go to Microsoft 365 admin center Users -> Active users -> Select the user -> Manage multifactor authentication -> Select the user -> Disable multi-factor authentication. M...

Copying Footers Between SharePoint Sites Using PnP PowerShell

Recently, I have been extensively working with SharePoint and the Patterns and Practices (PnP) PowerShell module. PnP has significantly simplified various tasks by providing easy-to-use command sets and thorough documentation. One particular task that PnP has made straightforward is copying a footer from one SharePoint site to another. This process can be achieved with just a few commands. Why Use PnP PowerShell? PnP PowerShell is a set of cmdlets designed to work with SharePoint Online and SharePoint on-premises. It simplifies the management and automation of common tasks and provides commands for nearly every aspect of SharePoint administration. The PnP module is especially useful for tasks that would otherwise require complex scripting or manual intervention. Copying a Footer with PnP PowerShell To copy a footer from one SharePoint site to another, follow these steps. This process involves exporting the footer template from the source site in XML format and...