Wednesday, September 2, 2009

MOSS 2007 webpart using CAML query

Here is a simple webpart using CAML query to fetch a particular value from a SharePoint List.
I have an announcement list and I am searching for a "Title" corresponding to a field called "Posted By" in the same list. I use the u2u CAML query builder to build CAML queries.Here goes my webpart code:

using System;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using System.Web.UI;
using System.Web.UI.WebControls.WebParts;
using Microsoft.SharePoint;
using System.Data;
using System.Diagnostics;
using System.Web.UI.WebControls;
using Microsoft.SharePoint.Utilities;
namespace WSPBuilderProject1
{
[Guid("be9d2bda-11ef-43e2-bad3-85e5238a1755")]
public class WebPartFeature1 : Microsoft.SharePoint.WebPartPages.WebPart
{
Label lbl;
protected override void CreateChildControls()
{
try
{ //Initializing my site collection url
string sUrl = "http://sm-cala-csx01:5318/sites/HRDep";
//Always use the "using" statement to ensure proper disposal of the SPWeb and SPSite objects.
using (SPSite siteCollectionOuter = new SPSite(sUrl))
{
//Initializing my web app url since my lists are in a subsite called Docs
using (SPWeb webapp = siteCollectionOuter.AllWebs["/sites/HRDep/Docs"])
{
//The list Ann Log to which I want to add data after Item is added to list Announcements
SPList annLog = webapp.Lists["Announcements"];
//Adding the Title field of the new item to my Ann Log list
SPQuery getItem = new SPQuery();
getItem.Query = "Rxiyer";
SPListItemCollection items = annLog.GetItems(getItem);
lbl = new Label();
if (items != null)
{
string strTitle = SPEncode.HtmlEncode(items[0].DisplayName.ToString());
//HtmlEncode(items["Title"].ToString());
//QueryFieldNames["Title"].ToString();
lbl.Text = strTitle;
}
else
{
lbl.Text = "error";
}
this.Controls.Add(lbl);
}
}
}
catch (Exception ex)
{
//Writing any exceptions to the event viewer under a source called SharePoint Features
if (!EventLog.SourceExists("SharePoint Features"))
EventLog.CreateEventSource("SharePoint Features", "Application");
EventLog.WriteEntry("SharePoint Features", ex.ToString());
}
}
}
}

No comments: