SPLists, SPListItems, and SPFields
In the previous post we accessed the SharePoint we and site objects. Now that we are in the web we can access lists, list items, and individual fields in the list item.
The first thing to do is get a list object:
Dim objList As SPList = objWeb.Lists("CustomList")
To create a list object you can pass in the name of the list into the Lists Collection.
To filter the items that you want to access in the list you can create a CAML query.
Dim objQuery As SPQuery = New SPQuery()
objQuery.Query = "<where><gt>" & _
"<fieldref name=" & ProjectedValue & />" & _ "<value type='number'>500</value> </gt> </where>"
This query will only return rows that have a 'Projected Value' greater than 500.
To return the rows from the query you need to create a ListItemCollection.
Dim objListItemCollection As SPListItemCollection = objList.GetItems(objQuery)
You fill the ListItemCollection by calling the GetItems method of a Sharepoint List object and passing in a CAML query. Once you have the ListItemCollection you can iterate through it or grab items by ID.
Once you have a ListItem you can get access to the individual fields for that list item.
Dim objItem As SPListItem = objListItemCollection.Items(1)
Dim strItemName As String = objItem.GetFormattedValue("Name")
The GetFormattedValue returns a clean string no matter what the field type is.
You can also get field values back in this manner:
Dim strItemName As String = objItem("Name")
This is not always guaranteed to return a clean string of the value.
You can set fields for a list item in a similar manner:
objItem("Name") = "Brand New Field"
You can quickly manipulate values in a list using these objects and the methods they provide.
Labels: SharePoint Object Model, SPFields, SPListItems, SPLists
2 Comments:
I get exceptions trying to access the built-in "Description" field in a Picture Library using an SPListItem. I can access other fields, and custom fields, but there seems to be some sort of problem with the Description field. It throws an exception both with GetFormattedValue, and with the raw item["Description"].
As far as I know you should be able to access the Description field without any problems. What kind of error do you get?
Post a Comment
Subscribe to Post Comments [Atom]
<< Home