Programmatically Refresh Content Query Web Part

In this article we can explore a real-life scenario of refreshing Content Query Web Part programmatically.

SharePoint-1.jpg

I hope the reader has a good knowledge of:

  1. SharePoint page editing
  2. Web Part insertion
  3. Web Part creation using Visual Studio
  4. Web Part Deployment

Scenario

The following are the scenario items:

  1. A home site with 2 web parts, project button web part and Content Query (CQ) web part
  2. 2 project sites, each with Tasks list
  3. On the click of a button, the specific project tasks should be shown in the CQ web part

How to do that?

SharePoint-2.jpg

What is Content Query web part?

A Content Query web part allows list querying and it is a part of Enterprise Content Management (ECM) functionality. You can add the web part from the Content Query category. You need to enable the Publishing feature to access the web part.  Within code, the web part is called "Microsoft.SharePoint.Publishing.WebControls.ContentByQueryWebPart".

Step 1: Create Project Sites

Create 2 project sites of template Team Site and add some tasks into it.  Make sure you remember the URLs.

The Project 1 Tasks list:

SharePoint-3.jpg

The Project 2 Tasks list:

SharePoint-4.jpg
           
Step 2: Design Project Buttons web part

Open Visual Studio and do the following:

  1. Create a new Visual Web Part project of type Farm Solution
  2. Add a reference to the "Microsoft.SharePoint.Publishing" namespace
  3. Delete the existing web part inside the project
  4. Create a new Visual Web Part and name it "ProjectButtonsWebPart"
  5. Replace the Page Load event with the following code:
     

    privatestatic Dictionary<string,string> _projectUrl; 

    protectedvoid Page_Load(object sender, EventArgs e)

    {

        _projectUrl =new Dictionary<string,string>();

        _projectUrl.Add("Project 1", "/projectsite1");

        _projectUrl.Add("Project 2", "/projectsite2");

     

        // Create UI controls for Projects

       foreach (string project in _projectUrl.Keys)

        {

            Button button =new Button();

            button.Text = project;

            button.Click += button_Click;

           this.Controls.Add(button);

        }

    } 
     

  6. Add the following method for the button click event handler.
     

    privatevoid button_Click(object sender, EventArgs e)

    {

       string url = _projectUrl[(senderas Button).Text];

     

        SPSite site = SPContext.Current.Site;

        SPWeb web = site.RootWeb;

        web.AllowUnsafeUpdates = true;

        SPLimitedWebPartManager manager = web.GetLimitedWebPartManager("SitePages/Home.aspx", System.Web.UI.WebControls.WebParts.PersonalizationScope.Shared);

     

       foreach (System.Web.UI.WebControls.WebParts.WebPart w in manager.WebParts)

           if (w is Microsoft.SharePoint.Publishing.WebControls.ContentByQueryWebPart)

            {

                Microsoft.SharePoint.Publishing.WebControls.ContentByQueryWebPart cwp = (was Microsoft.SharePoint.Publishing.WebControls.ContentByQueryWebPart);

     

                SPWeb targetWeb = site.OpenWeb(url);

                cwp.WebUrl = targetWeb.ServerRelativeUrl;

                //set the guid of the list

                cwp.ListGuid = targetWeb.Lists["Tasks"].ID.ToString();

     

                PublishingWeb pweb = PublishingWeb.GetPublishingWeb(targetWeb);

                cwp.Update(pweb);

                manager.SaveChanges(w);

            }

     

        ClientScriptManager cs = Page.ClientScript;

        String csName ="ReloadClientScript";

        Type csType =this.GetType();

     

       if (!cs.IsStartupScriptRegistered(csType, csName))

        {

            StringBuilder csText = new StringBuilder();

            csText.Append("<script type=\"text/javascript\">");

            csText.Append("this.location.reload(); </");

            csText.Append("script>");

            cs.RegisterStartupScript(csType, csName, csText.ToString());

        }

    }
     

  7. Ensure you have the following namespaces included.
     

    using System.Web.UI;

    using System.Web.UI.WebControls;

    using System.Web.UI.WebControls.WebParts;

    using Microsoft.SharePoint;

    using Microsoft.SharePoint.Publishing;

    using Microsoft.SharePoint.WebPartPages;
     

  8. Resolve any namespace issues like "System.Web.UI.WebControls.WebParts.WebPart"
  9. Build the project
  10. Deploy the project
  11. Insert the Project Buttons web part to the home page. It looks as in the following.

    SharePoint-5.jpg

Step 3: Insert the Content Query web part

Now we can insert the Content Query web part into the home page.  Open the page in edit mode and insert a web part from the Content Rollup group as shown below.

SharePoint-6.jpg

Edit the web part and make the Link property empty.

SharePoint-7.jpg

Now the page looks like:

SharePoint-8.jpg

Step 4: Test the Buttons

Now click on the Project 1 button and you should see the Content Query web part updated with tasks.

SharePoint-9.jpg

Now click on the Project 2 button and you should see the tasks changed with Project Site 2.

SharePoint-1.jpg

To summarize the activities, please note the following:

  1. The Project Buttons web part has 2 hard coded paths inside it
  2. On the click of the button, the Content Query web part is refreshed by changing the List ID property
  3. After the button click is processed, a client-side startup script is registered to reload the page
  4. Now on clicking the button, the content query web part will display a tasks list from the corresponding project site.

References

http://msdn.microsoft.com/en-us/library/ff650512.aspx 

Summary

In this article we have explored a typical real-world scenario of refreshing a web part from another web part.  I hope this will be useful to you in SharePoint development. The source code is attached along with the article.

Up Next
    Ebook Download
    View all
    Learn
    View all