Custom Control In SharePoint 2010 to Filter Lists based on Site Name (Not title)

Scenario, you have a list of say Projects on the top level site, you want to render medadata about the project from this list on each site below it. You are storing the site name a part of this metadata. So you will need a custom control to get site name when loading page and pass that name to a filter using the DVWP paramaters.

Here is the code, build and compile in VS 2010 and deploy dll to GAC. user VS 2010 Server Control Project.

image

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;

namespace ctlGetSiteName
{
    [DefaultProperty("Text")]
    [ToolboxData("<{0}:ctlGetSiteName runat=server></{0}:ctlGetSiteName>")]
    public class ctlGetSiteName : WebControl
    {
        [Bindable(true)]
        [Category("Appearance")]
        [DefaultValue("")]
        [Localizable(true)]
        private String GetCurrentSiteName()
        {
            SPWeb currentWeb = SPContext.Current.Web;

            {
                string CurrentWebName = currentWeb.Name;
                if (!string.IsNullOrEmpty(CurrentWebName))
                {
                    return CurrentWebName;
                }
            }
            return null;
        }

        public string Text
        {
            get
            {

                return GetCurrentSiteName();
            }

        }

        protected override void RenderContents(HtmlTextWriter output)
        {
            output.Write(Text);
        }

    }
}

Note: it seemed that for this to work the name space and public class needed to be same name, not sure if so but I ran out of time to double check.

Now to use the control, add this line to top of aspx page that you wish the control to render on. The tag prefix can be anything you like.

<%@ Register tagprefix="BP" namespace="ctlGetSiteName" assembly="CustomControlPullSiteName, Version=1.0.0.0, Culture=neutral, PublicKeyToken=d8a14cc27b3bad55" %>

Add this line to the end of the code (usually end of page) within “ContentPlaceHolderId="PlaceHolderMain" just above the </asp:Content> tag as follows.
<BP:ctlGetSiteName runat="server" id="ctlGetSiteName1"/>
</asp:Content>

Create a parameter on the DVWP called Site name pointing to the control in the parameter wizard pick list.

Now filter the list using the parameter and the Site Name column of the list.

But first you will need to add the list to the page, but the list is from another site, the one above it. No problem, save the list as a web part using SPD then add it to the sub site using SPD. I know the instructions are cryptic but I am running out of time.

Advertisements