Thursday, August 13, 2009

using SPContext.Current.List

Scenario:
Someone asked me an interesting question , he said he knows about SPContext.Current.Site and SPContext.Current.Web objects and how to use them.

but he is confused where can we use SPContext.Currect.List or SPContext.Current.ListId etc.

Solution:
Its was pretty simple to quickly show him how to use it in a Custom Application List Setting page. Code below.

Note : In layout pages you need to pass the List=<ListGUID> as Query parameter
( Thanks for Chaitu for pointing it out )

Also you can use the list context in any webpart which is sitting on any list pages ( EditForm.aspx , DisplayForm.aspx or AllItems.aspx ) , here you need not to have anything Query parameter for the list guid

ASPX:

<%@ Assembly Name="SPCustomField, Version=1.0.0.0, Culture=neutral, PublicKeyToken=7668d5f62402984f"%> 
<%@ Page Language="C#" Inherits="TestContext.ListSettingTest" MasterPageFile="~/_layouts/application.master" %>

<asp:Content ID="Content1" ContentPlaceHolderId="PlaceHolderMain" runat="server">
<asp:Label ID="lblListName" runat="server" Text=""></asp:Label>
</asp:Content>
Codebehind:
using System;
using Microsoft.SharePoint;
using System.Web.UI.WebControls;

namespace TestContext
{
public partial class ListSettingTest : System.Web.UI.Page
{
protected Label lblListName;
protected void Page_Load(object sender, EventArgs e)
{
lblListName.Text = "List Name : " + SPContext.Current.List.Title;
}
}
}
Result:
test

1 comments:

Unknown August 13, 2009 at 11:53 PM  

I would like to add to it.. SPContext.Current.List is also widely used in the code behind of layout pages. For example if you want to develop a layout page that enhances/modifies the functionality of default document library or a list, you pass in the list Guid as a perameter in the URL (List = whatever GUID for that list) and from the layout page, get to the list using SPContext.Current.List