In code how can I access a list e.g "MyList" in sharepoint, then iterate through this list items and get the value of a particular column on that list e.g the "URL" column?
To retrieve all items from a list and iterate through each one, the best solution would be as follows (assuming that this code is run as part of a feature):
public override void FeatureActivated(SPFeatureReceiverProperties properties)
{
using(SPSite site = properties.Feature.Parent as SPSite)
{
SPList list = site.RootWeb.Lists["ListName"];
SPListItemCollection items = list.Items;
foreach (SPListItem listItem in items)
{
Response.Write(SPEncode.HtmlEncode(listItem["Url"].ToString()) +"<BR>");
}
}
}
But if the list is very large, it would be better to paginate through the list items:
public override void FeatureActivated(SPFeatureReceiverProperties properties)
{
using(SPSite site = properties.Feature.Parent as SPSite)
{
SPList list = site.RootWeb.Lists["ListName"];
if(items.ItemCount > 100)
{
SPQuery query = new SPQuery();
query.RowLimit = 100;
int index = 1;
do
{
SPListItemCollection items = list.GetItems(query);
foreach (SPListItem listItem in items)
{
Response.Write(SPEncode.HtmlEncode(listItem["Url"].ToString()) +"<BR>");
}
query.ListItemCollectionPosition = items.ListItemCollectionPosition;
index++;
} while (query.ListItemCollectionPosition != null);
}
else
{
SPListItemCollection items = list.Items;
foreach (SPListItem listItem in items)
{
Response.Write(SPEncode.HtmlEncode(listItem["Url"].ToString()) +"<BR>");
}
}
}
}
This is based on the Microsoft's Best Practices for SharePoint.
From this blog post:
The correct way to do it is to store the Items property return value in a SPListItemCollection variable. With this the database is only queried once and we will then iterate over the result set that is stored within the collection object. Here is the changed sample code:
SPListItemCollection items = SPContext.Current.List.Items;
for(int i=0;i<100 && i<items.Count;i++) {
SPListItem listItem = items[i];
htmlWriter.Write(listItem["Title"]);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With