Read / Fetch / Retrieve data from SharePoint list programmatically using caml query

Posted: March 5, 2013 in My Work, News
Tags: , , , , , , , , , , , ,

Quick and Easy, just make sure to type the exact name of the Lists \ Libraries inside the code:

  • Open VS 2010 and Create new Project as Visual Web Part Project.
  • 3 tips need to be consider and that is : make sure .Net Framework is 3.5 – Platform Target to be 64 bit or Any CPU – last one is to Add Microsoft.SharePoint.dll in the reference.
  • In ASCX File, add following code:
    <ul><%=OutPut %></ul>
  • In CS File, add following code, I have used CAML Query Bulider to get below query:

public partial class VisualWebPart1 : WebPart

{
public string OutPut;
public VisualWebPart1()
{
}

protected override void OnInit(EventArgs e)
{
base.OnInit(e);
InitializeControl();
}

protected void Page_Load(object sender, EventArgs e)
{
SPSite spSite = new SPSite(“Site Name”);

SPWeb oWebSite = spSite.OpenWeb();
SPDocumentLibrary oDocumentLibrary = (SPDocumentLibrary)oWebSite.Lists[“List \ Library Name”];
SPQuery query = new SPQuery();
query.RowLimit = 5;

query.Query = “<Where><IsNotNull><FieldRef Name=’Title’ />” +
“</IsNotNull></Where>” +
“<OrderBy><FieldRef Name=’Modified’ Ascending=’False’ /></OrderBy>”;

SPListItemCollection colitem = oDocumentLibrary.GetItems(query);

foreach (SPListItem oItem in colitem)
{
OutPut = OutPut + “<li><a href=’URL if needed” + oItem[“ows_LinkFilename2”].ToString() + “‘>” + oItem[“Title”].ToString() + ” ” + “</a></li>”;
}
}
}

Happy Coding.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s