Eric Di Bari
Eric Di Bari

Reputation: 3867

Access list data through SharePoint Web Part

I'm building a custom web part in SharePoint 2007. It needs to access specific list item data and then format and style the output.

I'm developing the web part in C#, and would like the solution to be self-contained. How do I access list data from this web part? Can I use a SOAP request and process it in C#? Should I be pulling list data through a web service (such as getlistitems)?

Upvotes: 2

Views: 8094

Answers (2)

theChrisKent
theChrisKent

Reputation: 15099

Use the object model like this:

SPList list = SPContext.Current.Web.Lists(LISTNAME);
SPQuery query = new SPQuery() { Query = "<Where>...</Where>", ViewFields = "<FieldRef Name='Title' />" };
SPListItemCollection items = list.GetItems(query);

Then just use the SPListItemCollection. You will need to replace the Query text with a CAML query (leave off the <Query> element). A good way to generate the CAML needed is to use a free tool like this one:

http://www.u2u.net/res/Tools/CamlQueryBuilder.aspx

Upvotes: 1

Justin Niessner
Justin Niessner

Reputation: 245399

Since you're building a SharePoint Web Part, you should access the list and its data via the SPList class.

The linked document provides a short example of how to properly get a list from the current SharePoint site.

Upvotes: 1

Related Questions