Hiding Custom Web Part If Returned Data Is Empty

In this article, I will show how to hide a web part if the returned data from SharePoint list is empty.

First thing, what I use to implement the look and feel of items inside my web part is a div tag that runs at server, as the following:

<div id=”ReturnedData” runat=”server” name=”ReturnedData”/>

That’s all good, when you get items inside your query, and loop through each item, you add in your C# code: ReturnedData.InnerHTML+= …., and you format the item as you want, I know you get the idea!

Now for the fun part of hiding your web part if the items count = 0, so if the items count = 0, the div won’t have any HTML inside, right? So we can catch that in JavaScript, like the following:


function HideIfEmpty() {

var ReturnedData= document.getElementsByName(“ReturnedData”);

if (ReturnedData[0].innerHTML == “”) {

var chrome = ReturnedData[0].parentNode.parentNode.parentNode;

chrome.style.display =“none”;





That’s it, but how have we done it?

The function HideIfEmpty gets the element by the name attribute, which is ReturnedData. It contains more than one element inside, the first element contains all the innerHTML, so we get the innerHTML by searching for the first element in the array; ReturnedData[0] if equals =”” then we don’t have any data returned.

Now we need to get a reference to the web part chrome element, which is an ancestor of the div ReturnedData, so we get it by navigating up in the hierarchy three times., then hide the chrome by executing: chrome.style.display=”none”, this is how we hide elements in JavaScript.

Note the _spBodyOnLoadFunctionNames(“HideIfEmpty”) is used to execute the function once we load the page, this is how you execute JavaScript functions on page load in SharePoint.

Hope it helps someone out there.

M . D

About these ads

About Mohamed Derhalli

SharePoint Administrator, Developer in Amman, Jordan.

Posted on June 7, 2013, in Uncategorized. Bookmark the permalink. 1 Comment.

  1. That was a great tip and done in my project. thank you

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s


Get every new post delivered to your Inbox.

%d bloggers like this: