I have to get values programmatically from the discussions list. When I tried this code it is giving the values of replies.
SPList oSpListPost = oSPWeb.Lists["Discussions List"];
SPListItemCollection oSpListItemClnPost = oSpListPost.Items;
foreach (SPListItem post in oSpListItemClnPost)
{
SPField field = post.Fields.GetField("Body");
}
The "parent" discussion is a folder with attached metadata, not a list item. You will probably want to get the associated folders in the list instead of the individual list items.
Related
My friend is having a problem in SharePoint that he is accessing the SharePoint sqlserver database.
The code is :
SPListItemCollection collListItems = oList.Items;
foreach (SPListItem item in collListItems)
{
Response.WriteLine(item[0]);
Response.WriteLine(item[1]);
Response.WriteLine(item[2]);
Response.WriteLine(item[3]);
}
In the foreach loop, the item variable does not have the Length nor the Count property and he wants to write generalized code, but is unable to loop on item.
Can anybody please tell that how can we iterate the item inside the foreach loop?
Currently it is looking like item(0) item(1) and so on.
Not sure why you want to do that since there are a lot of default fields but here is how you to do it:
foreach (SPField field in oList.Fields)
{
Response.WriteLine(item[field.Id])
}
I have a List that stores items in a folder hierarchy.
I notice that SPFolder.Files.Count is always zero.
Is there a way to find out how many list items are there in a folder?
I presume you are looking for direct children and not descendants (like items within a sub-folder).
Do you also want to include sub-folders in the count? In which case you can use: SPFolder.ItemCount.
If you just want only the direct child listItems which are not subfolders then you can do something like the following:
using (SPSite site = new SPSite(mySPSite))
{
SPWeb web = site.OpenWeb();
SPList list = web.Lists[myList];
SPFolder folderInstance = list.RootFolder.SubFolders[folderUrl];
SPQuery query = new SPQuery() ;
query.Folder = folderInstance;
SPListItemCollection items = list.GetItems(query) ;
Console.WriteLine(items.Count);
}
I haven't tried it. You might have to add a where clause to eliminate folders, if the query is returning that.
If you want to include all list-items, even within subfolders, set the SPQuery.ViewAttributes field as query.ViewAttributes = "Scope=\"Recursive\"";
Did you try to get the SPListItem from the SPFolder and check the values from the SPBuiltInFieldId.ItemChildCount and SPBuiltInFieldId.FolderChildCount fields?
Something like this:
SPFolder folder = ...;
int? noOfItems = folder.Item[SPBuiltInFieldId.ItemChildCount] as int?;
int? noOfFolders = folder.Item[SPBuiltInFieldId.FolderChildCount] as int?;
See
SPBuiltInFieldId.ItemChildCount Field
SPBuiltInFieldId.FolderChildCount Field
for more info.
From Microsoft
Using the SPList.ItemCount property is
the recommended way to retrieve the
number of items in a list. As a side
effect of tuning this property for
performance, however, the property can
occasionally return unexpected
results. For example, if you require
the exact number of items, you should
use ...
I wonder if the same applies to SPFolder.ItemCount ?
I'm trying something very simple - accessing my SharePoint list's items and their properties.
However, SPListItem.Properties count is zero for all normal lists. Everything works as expected for document and pages libraries. So, if the list items are based on document type, all is good. If they are based on item, properties are not returned.
I've tried in two environments, with new sites created from OOTB publishing templates, with new lists which are based on OOTB content types etc. Always the same thing.
Right amount of SPListItems is always returned. Title and Name are fine. It's just that the .Properties hashtable is totally empty.
In desperation, I wrote a web part that outputs the following (ugly!) diagnostics.
foreach (SPList list in SPContext.Current.Web.Lists)
{
foreach (SPListItem item in list.Items)
{
Label label = new Label();
label.Text = "Name: " + item.Name + "Property count: " + item.Properties.Count;
this.Controls.Add(label);
}
}
The only observation is that it works exactly as I described earlier. I just share the code to show that this is the most basic operation imaginable.
Here is sample output - I've added the line breaks for readability ;-)
Name: Test Property count: 0
Name: default.aspx Property count: 21
Obviously item "Test" is an item based list item and default.aspx is a page.
Has anyone ever encountered anything like this? Any ideas?
item["FieldName"] is the canonical way to get a value of a metadata column in a SharePoint list. If you need to get the list of available fields for a SharePoint list, check the parent SPList object's Fields property which is a collection of the fields in this list. Each of those field objects will have a property called InternalName and that is what you should use to access its value when you are working with an instance of SPListItem.
Are you trying to get the field Values? Sadly, they are not strongly typed:
string ModifiedBy = (string)item["Author"];
To get the proper names of the fields (they have to be the internal names), go to the List and then List Settings. You will find the List of Columns there. Click on any Column Name to go to the Edit Page, and then look at the URL in the Address Bar of your Browser. At the very end, there should be a parameter "Field=Editor" or similar - that's your internal field name.
If you wonder why a field like "Test Field" looks strange, that is because Sharepoint encodes certain characters. A Space would be encoded to x0020 hence the Internal Name for "Test Field" is "Test_x0020_Field".
In order to get the proper field type to cast to:
string FieldType = item["Author"].GetType().FullName;
(The Intermediate Window in Visual Studio is tremendously helpful for this!)
I have found the following extension to the SPListItem class to be very helpful.
internal static class SharePointExtensions
{
internal static Dictionary<string, object> PropertiesToDictionary(this SPListItem item)
{
// NOTE: This code might be temping - but don't do it! ...itdoes not work as there are often multiple field definitions with the same Title!
// return item.Fields.Cast<SPField>().ToDictionary(fld => fld.Title, fld => item[fld.Title]);
Dictionary<string, object> dict = new Dictionary<string, object>();
var fieldNames = item.Fields.Cast<SPField>().Select(fld => fld.Title).Distinct().OrderBy(sz => sz).ToArray();
foreach (fieldName in fieldNames)
dict.Add(sz, item[fieldName]);
return dict;
}
}
with it you can simply do:
item.PropertiesToDictionary()
...and you will have a nice Linq dictionary object that will work just the way you'd expect. Is it a little heavy-weight / low-performance? Sure. Are most people willing to make that trade-off? I think so...
Do you run SPListItem.Update() or .SystemUpdate() after setting the properties?
If you want to get an object out of a SPField of a SPListItem you've got to do like this:
SPField field = ((SPList)list).Fields.GetField("FieldName");
object fieldValue = field.GetFieldValue(((SPListItem)item)[field.Title].ToString());
The ListItem.Properties hashtable will be empty unless you assign to it.
SPListItem item = properties.ListItem;
item.Properties["Key"] = "value";
int total = item.Properties.Count;
Answer:
"total == 1"
SPList yourList = web.Lists["Your list name"];
string sColumnValue = oSPListItem[yourList.Fields["yourSiteColumn display
name"].InternalName].ToString();
Hi I have a question about SPListItem and how to retrieve values from it. In the view I am in I can access the "Article" no problem but when I try to access the "Link" I can an error saying object not initalized. I don't understand whats going on? Why can I not get the Link when I can get the Article field. Here is the code I am using:
SPList myList = eachWeb.Lists["Listings"];
SPListItemCollection myItemCollection = myList.GetItems(myList.Views["Active Announcements"]);
for (int i = 0; i < myItemCollection.Count; i++)
{
SPListItem realitem = myItemCollection[i];
writer.Write(realitem["Article"].ToString()+"<BR>"); // Works without the bottom line
writer.Write(realitem["Link"].ToString()+"<BR>"); // Causes error
My view contains a column for both Article and Link. Thank you.
The internal name of a field may not match the display name; especially if you've changed the name after creating the list. Try debugging and taking a look at the names of the fields in the SPListItemCollection and see if you can figure out which one it is there.
Scenario: Document library in SharePoint with column x of "Person or Group" type. From within a VBA macro (or VSTO add-in) we're trying to access the MetaProperty on the document to set/get the user name. Any attempt to access the value via the ContentTypeProperties collection throws a
Type MisMatch error (13).
The Type property of the MetaProperty object says it's msoMetaPropertyTypeUser. I cannot find any examples of how to work with MetaProperties of this type. Anyone have any experience with this?
Thanks!
You should be able to just do something like this:
using (SPSite site = new SPSite("http://yoursite/subsite"))
{
using (SPWeb web = site.OpenWeb())
{
SPList list = web.Lists["DocLibraryName"];
SPListItemCollection items = list.GetItems(list.Views["All Documents"]);
foreach (SPListItem item in items)
{
item["Modified By"] = "Updated Value";
}
}
}
Any metadata for a document should be available by indexing the column name of the SPListItem.
I did it.
The trick here is actually to know that if you put a string corresponding to the user index in MOSS users in the custom property of the Word document, MOSS will recognize it and find the corresponding user to map the field.
so you just need to call http:///_vti_bin/usergroup.asmx
use the function GetUserInfo and retrieve the user index (ID) from it.
MOSSusergroup.UserGroup userGroupService = new MOSSusergroup.UserGroup();
userGroupService.Credentials = System.Net.CredentialCache.DefaultCredentials;
System.Xml.XmlNode node = userGroupService.GetUserInfo(userLogin);
string index = node.FirstChild.Attributes["ID"].Value;