I have sharepoint list I have added a column "DistributionId" as a single line of text. I can see it in the fieldvalues when I debug. I can see it being set by the line listItem.FieldValues["DistributionId"] = "test";. However this is not updated in SharePoint and reverts to a blank value when the execute query is fired underneath. Also value is not set in SharePoint when checked directly. Any idea what I am doing wrong?
using (ClientContext clientContext = new ClientContext(SpEndPointUri))
{
Site site = clientContext.Site;
Web web = clientContext.Web;
List list = clientContext.Web.Lists.GetByTitle(library);
CamlQuery query = new CamlQuery();
query.ViewXml = #"<View><Query><Where><Eq><FieldRef Name='ID' /><Value Type='Counter'>" + documentId + #"</Value></Eq></Where></Query></View>";
ListItemCollection items = list.GetItems(query);
// Retrieve all items in the ListItemCollection from List.GetItems(Query).
clientContext.Load(items, ic => ic.Include(i => i, i => i["DisplayName"], i => i["Id"], i => i["HasUniqueRoleAssignments"]));
clientContext.ExecuteQuery();
ListItem listItem = items[0];
clientContext.Load(listItem);
clientContext.ExecuteQuery();
listItem.FieldValues["DistributionId"] = "test";
listItem.Update();
clientContext.ExecuteQuery();
clientContext.Load(listItem);
clientContext.ExecuteQuery();
}
Use ListItem.Item property to set field value instead. ListItem.FieldValues property is used only for getting a collection of key/value pairs containing the names and values for the fields of the list item.
How to update ListItem field value:
var list = ctx.Web.Lists.GetByTitle(listTitle);
var listItem = list.GetItemById(listItemId);
listItem[fieldName] = fieldValue;
listItem.Update();
ctx.ExecuteQuery();
Related
Is there a Sharepoint API to get entire content of files/folders for a particular folder at once ?
I don't want to use GetFolderByServerRelativePath recursively.
If don't want to use GetFolderByServerRelativePath, you can use CSOM with CAML Query like this:
string password = "pwd";
string account = "user#Tenant.onmicrosoft.com";
var secret = new SecureString();
foreach (char c in password)
{
secret.AppendChar(c);
}
using (ClientContext ctx = new ClientContext("https://Tenant.sharepoint.com/sites/sitename"))
{
ctx.Credentials = new SharePointOnlineCredentials(account,secret);
Web web = ctx.Web;
ctx.Load(web);
ctx.ExecuteQuery();
List list = web.Lists.GetByTitle("Documents");
ctx.Load(list);
ctx.ExecuteQuery();
Folder folder = web.GetFolderByServerRelativeUrl(web.ServerRelativeUrl + "/shared%20documents/");
ctx.Load(folder);
ctx.ExecuteQuery();
CamlQuery camlQuery = new CamlQuery();
camlQuery.ViewXml = #"<View Scope='RecursiveAll'>
<Query>
</Query>
</View>";
camlQuery.FolderServerRelativeUrl = folder.ServerRelativeUrl;
ListItemCollection listItems = list.GetItems(camlQuery);
ctx.Load(listItems);
ctx.ExecuteQuery();
foreach (var item in listItems)
{
Console.WriteLine(item.FieldValues["FileRef"].ToString());
}
}
will return all folders/subfolders/files together, hopefully, this is what you need.
I have two lists and one event receiver. The event receiver sets a column of the list to a unique identifier (combo of the content type and the item id).
In the other list I use query string and the newform to set a field to the very same unique identifier above. I also gather some more info in that newform I want to work with.
How can I query a list without knowing the ID, but I have another unique id to single out from the other items so I can work with it just as SPitem firstitem below so I can find the other fields.
Getting my first item to get the unique title:
SPSite currentSite = SPContext.Current.Site;
SPWeb web = currentSite.OpenWeb();
string queryString = Request.QueryString["uniqueID"];
SPList firstList = web.Lists["My First List"];
SPItem firstItem = firstList.Items.GetItemById(Convert.ToInt32(queryString));
this is the unique title I want to query second list with:
string uniqueTitle = firstItem["Title"].ToString();
getting my second list up, ready for action:
SPList secondList = web.Lists["My Second List"];
Thanks
ANSWER:
// open the second list
SPList secondList = web.Lists["My Second List"];
// Query the second list for the item
SPQuery myQuery = new SPQuery();
myQuery.Query = "<Where><Eq><FieldRef Name = \"Title\"/>" +
"<Value Type = \"Text\">" + uniqueTitle +
"</Value></Eq></Where>";
// Get a collection of the second list items selected by the query and pick the first (0) value as it should only return one!
SPListItemCollection secondlistItemCol = secondList.GetItems(myQuery);
SPListItem secondItem = secondlistItemCol[0];
You will want to use the GetItems command with an SPQuery object. It is not too complex to sort out with the MS code example below.
using System;
using Microsoft.SharePoint;
namespace Test
{
class ConsoleApp
{
static void Main(string[] args)
{
using (SPSite site = new SPSite("http://localhost"))
{
using (SPWeb web = site.OpenWeb())
{
// Build a query.
SPQuery query = new SPQuery();
query.Query = string.Concat(
"<Where><Eq>",
"<FieldRef Name='Status'/>",
"<Value Type='CHOICE'>Not Started</Value>",
"</Eq></Where>",
"<OrderBy>",
"<FieldRef Name='DueDate' Ascending='TRUE' />",
"<FieldRef Name=’Priority’ Ascending='TRUE' />",
"</OrderBy>");
query.ViewFields = string.Concat(
"<FieldRef Name='AssignedTo' />",
"<FieldRef Name='LinkTitle' />",
"<FieldRef Name='DueDate' />",
"<FieldRef Name='Priority' />");
query.ViewFieldsOnly = true; // Fetch only the data that we need.
// Get data from a list.
string listUrl = web.ServerRelativeUrl + "/lists/tasks";
SPList list = web.GetList(listUrl);
SPListItemCollection items = list.GetItems(query);
// Print a report header.
Console.WriteLine("{0,-25} {1,-20} {2,-25} {3}",
"Assigned To", "Task", "Due Date", "Priority");
// Print the details.
foreach (SPListItem item in items)
{
Console.WriteLine("{0,-25} {1,-20} {2,-25} {3}",
item["AssignedTo"], item["LinkTitle"], item["DueDate"], item["Priority"]);
}
}
}
Console.ReadLine();
}
}
}
Looking for a way to find a document registered in Sharepoint. I can find document in a documet library or list by following code.
SPSite oSPSite = new SPSite(_serverUrl);
SPWeb oSPWeb = oSPSite.OpenWeb();
SPList oSPList;
SPListItemCollection oSPListItemCollection;
oSPList = oSPWeb.Lists["Listname"];
SPListItem listItem = null;
listItem = oSPList.GetItemByUniqueId(new Guid(spGuid));
But do i need to iterate trough all list if i dont know in which list the document is registered or is there a more efficient way.
If the UniqueId is the only information you have then you have to create a SPSiteDataQuery to retrieve the URL of the document:
SPWeb web = // ...
SPSiteDataQuery q = new SPSiteDataQuery();
q.Query = String.Format(
"<Where><Eq><FieldRef Name='UniqueId' /><Value Type='Lookup'>{0}</Value></Eq></Where>",
spGuid);
q.Lists = "<Lists BaseType="1" />"; // restrict to document libraries
q.RowLimit = 1;
// q.Webs = "<Webs Scope='SiteCollection' />"; add to broaden the search on the whole site collection
q.ViewFields = "<FieldRef Name='EncodedAbsUrl' />";
DataTable tbl = web.GetSiteData(q);
if (tbl.Rows.Count == 0) throw new FileNotFoundException(...);
return tbl.Rows[0]["EncodedAbsUrl"];
Then you can load the SPFile (the document) with SPWeb.GetFile(string). If you just need the SPListItem you can access this via SPFile.Item.
If you don't know in what list the document is placed you will need to iterate over the available SPList objects from the SPWeb.
I'm using Sharepoint 2010 Object Model. I'm trying to retrive the content of a Custom List. Everything works fine except if when I try to retrieve a Choice Field.
When I try to retrieve the choice field, I got an PropertyOrFieldNotInitializedException exception...
Here is the code I'm using:
ClientContext clientContext = new ClientContext("https://mysite");
clientContext.FormsAuthenticationLoginInfo = new FormsAuthenticationLoginInfo("aaa", bbb");
clientContext.AuthenticationMode = ClientAuthenticationMode.FormsAuthentication;
List list = clientContext.Web.Lists.GetByTitle("mylist");
CamlQuery camlQuery = new CamlQuery();
camlQuery.ViewXml = "<View/>";
ListItemCollection listItems = list.GetItems(camlQuery);
clientContext.Load(listItems);
clientContext.ExecuteQuery();
foreach (ListItem listItem in listItems)
{
listBoxControl1.Items.Add(listItem["Assigned_x0020_Company"]);
}
var list = clientContext.Web.Lists.GetByTitle(listName);
clientContext.ExecuteQuery();
clientContext.Load(list.Fields, fields => fields.Include(field => field.Title));
clientContext.ExecuteQuery();
foreach (var field in list.Fields)
{
if (field.Title == "YourChoiceFieldName")
{
clientContext.Load(field);
clientContext.ExecuteQuery();
return ((FieldChoice) field).Choices;
}
}
When you read a ChoiceField in code , It will return a string array of selected choices. For example if you entered in the choice box of the column when you create it : "Company 1" ,"Company 2","Company 3 " , if user select option 1 & 2 , then returned array in code will contain "Company 1" and "Company 2" .You must change the code to the below :
foreach (ListItem listItem in listItems)
{
string[] values = (string[])listItem["Assigned_x0020_Company"];
foreach(string s in values)
{
listBoxControl1.Items.Add(s);
}
}
I'm trying to display the ListItems in a gridview.
Please help me in finding a way to access the list items.
using (SPSite site = new SPSite("http://mysitehere......"))
{
using (SPWeb web = site.OpenWeb())
{
SPList list = web.Lists["TestList"];
.......
.......
}
}
Please help me in accessing the list item values.
The below code should do the trick, get the full article from msdn here
using (SPSite site = new SPSite("http://mysitehere......"))
{
using (SPWeb web = site.OpenWeb())
{
SPList list = web.Lists["TestList"];
SPListItemCollection collListItems = list.Items;
foreach (SPListItem oListItem in collListItems)
{
string value = SPEncode.HtmlEncode(oListItem["Field1_Name"]);
// do something with value
}
}
}
You may use any of the below:
SPList list;
foreach (SPListItem item in list.Items)
{
string title = item["Title"];
}
SPQuery query = new SPQuery();
query.ViewFields = "<FieldRef Name='Title'/>";
SPListItemCollection items = list.GetItems(query);
foreach (SPListItem item in list.Items)
{
string title = item["Title"];
}
for (int i = 0; i < list.Items.Count; i++ )
{
string title = list.Items[i]["Title"];
}
From the performance point of view, I suggest using the SP Query as then you can specify which fields to fetch and whether or not to fetch any associated metadata with the list items. This results in fewer db calls.
Kind regards,
Use SPDataSource to display list items in a grid view, i.e. create and configure an SPDataSource object and bind it to a SPGridView control.
For displaying items in a gridview (if you don't want to use SPGridView), I would use the GetDataTable method, instead of using a foreach loop as many of the answers do.
if (items.Count > 0)
{
DataTable dt = items.GetDataTable();
GridView1.DataSource = dt;
GridView1.DataBind();
}
Well, I haven't done any sharepoint work, but I believe you can use:
foreach (SPListItem item in list.Items)
or
foreach (SPListItem item in list.GetItems(view)) // or query
or access by index or guid:
SPListItem item = list.Items[10];
SPListItem item = list.Items[guid];
The SPQuery approach as suggested by unknown(yahoo) is the way to go, however you should remember that the default rowlimit of SPQuery is 100:
try
{
using (SPSite site = new SPSite(theURL))
{
SPWeb web = site.OpenWeb();
SPList list = web.Lists["TheNameOfTheList"];
//search each ListItem where the date is after 1/1 2009
SPQuery query = new SPQuery();
//the default is 100, which is less then the expected max
query.RowLimit = 500;
// The U2U CAML Query builder rules :-)
query.Query = "<Where><Gt><FieldRef Name='StartDate' /><Value Type='DateTime'>";
query.Query += "2009-01-01T00:00:00Z</Value></Gt></Where>";
SPListItemCollection resultset = list.GetItems(query);
foreach (SPListItem item in resultset)
{
// do something
}
}
}
If you´re using .NET 3.5 I would recommend using the linq datasource together with the spgridview to bind splistitems to a gridview. Saves you a lot of time.
I have an example of this on my blog.
To display images you have to get the url of the image. Here is an example of that:
SPListItem item = GetItem();
string imagefieldhtml = item["NameOfImageField"].ToString();
ImageFieldValue imagefield = new ImageFieldValue(imagefieldhtml);
var url = imagefield.ImageUrl;
The url variable will now hold the image url.
Ok, I have solved the above issue. In my case I did not need to use the SPEncode.HTML, so I have commented out everything that's not needed. Here is the fixed code if anyone else needs it:
using (SPSite site3 = SPContext.Current.Site)
{
using (SPWeb web2 = site3.OpenWeb())
{
// SPWeb site3 = SPContext.Current.Site.RootWeb;
SPList list2 = web2.Lists["Configuration"];
SPListItemCollection collListItems = list2.Items;
foreach (SPListItem oListItem in list2.Items)
{
//string value = SPEncode.HtmlEncode.ToString(oListItem["List name"]);
string valueListName = oListItem["List name"].ToString();
string valueListURL = oListItem["List URL"].ToString();
}
}
}