Pages

Monday, October 20, 2008

Fetch list item using SPQuery

One of my friend has one scenario in which he has to change display text of one of the column of
Data Grid web part and Back color of Submit button quickly without much changes into code, so for finishing task quickly he approach below steps.

Normally we can keep all configuration values of project in web.config file to avoid deployment in small change cases.

The second way to do it is to keep these values in SharePoint List (values like Some display name
(webpart title, column header text, etc), color).

Example :

I have list with following 4 columns : Title, ElementID, Language, ElementType

In code, we can get any parameter value by calling the following function :

string webPartTitle = queryForName("ContractDetails_WebPart","WebPartTitle", "en").ToString();

This is very helpful technique in terms of small display changes because it removes overheads of going in the code again and deploying again.

public static string queryForName(string Keyword, string Type, string Language)
{
string Name = string.Empty;
SPWeb currentWeb = SPContext.Current.Web;
try
{
SPList elementList = currentWeb.Lists[_ElementList];
string queryString = "<Where><And><And><Eq><FieldRef Name=\"ElementID\" /><Value
Type=\"Text\">" + Keyword + "</Value></Eq><Eq><FieldRef Name=\"ElementType\" /><Value Type=\"Lookup\">" + Type +"</Value></Eq></And><Eq><FieldRef Name=\"Language\" /><Value
Type=\"Lookup\">" + Language + "</Value></Eq></And></Where>";

SPQuery query = new SPQuery();
query.Query = queryString;
SPListItemCollection results;
results = elementList.GetItems(query);
int itemsReturned = results.Count;

if (itemsReturned == 1)
{
foreach (SPListItem result in results)
{
Name = result[_ElementContent].ToString();
break;
}
}
else
{
Name = "";
}
return Name;
}
catch (Exception ex)
{
return Name;
}
}

No comments:

Post a Comment