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...

Dataverse Multi Choice Columns in PowerApps

We have been working with PowerApps, PowerApps and Dataverse and now I thought of sharing a few tips to ease your work if you are new to PowerApps + Dataverse as a combination. I will be sharing a few more tips in my upcoming blogs but to get started, Let’s take Multi Choice Columns this time. Unlike SharePoint or any other data source, Dataverse Multi choice columns are different so basically, I cannot go to my PowerApp and directly print selected value in a label. So, this is how you can show multi choice values in label. You need to use concat that allows to concat multiple selection. PowerApps has concat function that takes. Concat function syntax :  Concat (  Table ,  Formula  ) In my case I am trying to render a multi choice column values into a vertical gallery webpart. I have added a label control to a vertical gallery and then added below code.   Concat(ThisItem.ColumnName,Value & "") Hope this helps, Thanks, Keyur

SharePoint Migration : This content database has a schema version which is not supported in this farm

Today one of my client was expecting to restore a SharePoint Site Collection from and Database that he already took as a backup.  I followed below steps.           1.        Imported content database to SQL of the farm where the site is to be restored.           2.        Created a web application.           3.        Visited manage content database, set the current database property to offline.           4.        Click on add a new content database.           5.        Set the name of the content database same as the database that is imported to SQL.   SharePoint gave me below error. “ This content database has a schema version which is not supported in this farm." I tried to use powershe...