Monday, October 20, 2008

SharePoint development tips

Since I am working with SharePoint I thought of posting some development tips and tricks as I found so that I can easily recall them if I need it again for any reason.

  • How to retrieve a list from an existing site and iterate items in the list

SPSite _site = SPContext.Current.Site;
SPWeb _web = _site.OpenWeb();
SPList myList = _web.Lists["<List name>"];

foreach (SPListItem item in myList.Items)
{
String title = item["Title"];
// your implementation
}

  • Retrieve a list using SPQuery

Here the "Office" is a lookup field in the "Personnel" list.
So you need to use "FieldRef" and "Lookupid".

Check the implementation bellow.

SPQuery query = new SPQuery();
query.Query = "<Where><Eq><FieldRef Name='Office' LookupId='TRUE' /><Value Type='Lookup'>1</Value></Eq></Where>";

foreach (SPListItem personnel in teams.GetItems(query))
{
// your implementation
}

  • How to use "AND" property in SPQuery

Here I need to select items where Office = 1 and Team = 2.
Query looks like this.And note that the reference fields are lookup type.

SPQuery query = new SPQuery();
query.Query = "<Where>
<And>
<Eq><FieldRef Name='Office' LookupId='TRUE' /><Value Type='Lookup'>1 </Value></Eq>
<Eq><FieldRef Name='Team' LookupId='TRUE' /><Value>Type='Lookup'>2</Value></Eq>
</And>
</Where>";

No comments: