Save lookup value to SharePoint 2010 - sharepoint

I've figured out how to add a record into a library. The only thing I am trying to figure out is how (or maybe where) do I save a user's selection from a lookup list?
In the below code snippet, I am saving a new list item. It saves without error, but the fields "AwardType" and "AwardReason" are lookup fields and, although I do not get an error, nothing gets saved to them. How do I save to a lookup field selection from a user?
using (SPSite site = new SPSite(SPContext.Current.Web.Url))
{
using (SPWeb web = site.OpenWeb())
{
using (FileStream fs = (new FileInfo(fileUpload.PostedFile.FileName)).OpenRead())
{
SPList list = web.Lists["Awards"];
Hashtable ht = new Hashtable();
ht.Add("wfRecipientName", txtRecipientName.Text);
ht.Add("Office", txtOrganization.Value);
ht.Add("AwardType", ddAwardTypes.SelectedValue);
ht.Add("AwardReason", ddAwardReasons.SelectedValue);
SPFile destfile = list.RootFolder.Files.Add(fileUpload.FileName, fs, ht, false);
}
}
}

Storing a lookup's value is done with SPFieldLookupValue(ID, Value).
You need to store the object returned by this method in a list item field, not a property via a hash table. In my example below, Awards list is document library and AwardType is a field of type lookup.
SPList list = web.Lists["Awards"];
Hashtable ht = new Hashtable();
ht.Add("Office", "Chicago"); // standard property
SPFile file = list.RootFolder.Files.Add(System.IO.Path.GetFileName(FileUpload1.PostedFile.FileName), fs, ht, true);
SPListItem item = file.Item; // get the item for the just-added file.
// assign the lookup column using SPFieldLookupValue
item["AwardType"] = new SPFieldLookupValue(
Int32.Parse(DropDownList1.SelectedValue),
DropDownList1.Text);
item.Update(); // to save the lookup column.

Interestingly, the line
SPListItem item = file.Item; // get the item for the just-added file.
is key.
I had trouble when I used the code below - the lookup did not update consistently!?
file.Item["AwardType"] = new SPFieldLookupValue(
Int32.Parse(DropDownList1.SelectedValue),
DropDownList1.Text);

You must add the SPFieldLookUpValue as string to the HashTable, not the value of the Lookup.
Properties stored on HashTable other than int, string, date will not be parsed on Document creation.
SPFieldLookupValue v = new SPFieldLookupValue(item["lookUpField"].ToString());
Hashtable documentProperties = new Hashtable();
documentProperties.Add("key", v.ToString());
SPFile file = docLib.RootFolder.Files.Add("fileName", memoryStream, documentProperties, true);
The same can be done with complex objects as SPUser.
SPFieldUserValue userValue = new SPFieldUserValue(web, web.CurrentUser.ID, web.CurrentUser.LoginName);
documentProperties.Add("SPuSER", userValue.ToString());

Related

SharePoint - programmatically add list items can't set ID

I need to create new list item in sharepoint 2016 but while creating, on ID field, i'm getting this error: "This field cannot be updated". I'm not updating anything and i checked the list and it was empty too.
I left this field empty and it has 0 value by defualt like when i'm inserting new row in sql tables.
The ID field is a system field which will increase automatically when new item created, so no need to set ID field value, here is a code snippet which add new item with default Title field and ID field will be automatically generated with 1 as it is a empty list previously:
SPSite site = new SPSite("http://demoaam.contoso2016.com/sites/dev");
using (SPWeb web=site.OpenWeb() )
{
SPList list = web.Lists["TestList"];
SPListItem newitem = list.AddItem();
newitem["Title"] = "NewItemTitle";
newitem.Update();
}

How to retrieve publishing rollup image path in sharepoint object model

While using the traditional code to retrieve list items in SharePoint, Everytime I get an error whenever I try to read the value of publishing rollup image. My Code is as below:
SPWeb mySite = SPContext.Current.Web;
SPList myList = mySite.Lists["Quick Links"];
SPListItemCollection myItems = myList.Items;
for (int i = 0; i < myItems.Count; i++)
{
SPListItem item = myItems[i];
pageHTML += item["PublishingRollupImage"].ToString(); //error
}
use this method
item.GetFormattedValue("Rollup Image");
The array access (bracket) notation to access a field value accepts one of three values between the brackets:
The field's GUID (as a System.Guid)
The field's display name (as a string)
The field's index in the item's fields collection (as an integer)
When accessing a field by its internal name instead of by its display name, you should use the dedicated GetFieldByInternalName method to retrieve the field from the fields collection, then use the retrieved field's Id property to get the field's GUID and use that in the brackets.
item[item.Fields.GetFieldByInternalName("PublishingRollupImage").Id].ToString();

why i cant bind gridview directly from ListItemCollection Object?

I'm new to SharePoint List and i need to bind gridview using list item collection object like below
SPList splEmployees = SPContext.Current.Web.Lists["Employees"];
spgvEmployees.DataSource = splEmployees.Items;//or splEmployees.GetItems();
spgvEmployees.DataBind();
this is not success when i bind it to gridview contains Title and EmployeeID columns but it success when i remove EmployeeID column.
Try to use a SPDataSource instead.
SPDataSource myDatas = new SPDataSource();
myDatas.List = splEmployees;
spgvEmployees.DataSource=myDatas;
spgvEmployees.DataBind();

How to get all possible values for SPFieldLookup

I have a lookup field in sharepoint which just references another list. I wonder how do I programatically enumerate all possible values for this field?
For example, my lookup field "Actual City" refers list "Cities" and column "Title", I have 3 cities there. In code I would like to get list of all possible values for field "Actual City", smth like (metacode, sorry):
SPFieldLookup f = myList["Actual City"];
Collection availableValues = f.GetAllPossibleValues();
//this should return collection with all cities a user might select for the field
I wrote some code to handle this for my project just the other day. Perhaps it will help.
public static List<SPFieldLookupValue> GetLookupFieldValues(SPList list, string fieldName)
{
var results = new List<SPFieldLookupValue>();
var field = list.Fields.GetField(fieldName);
if (field.Type != SPFieldType.Lookup) throw new SPException(String.Format("The field {0} is not a lookup field.", fieldName));
var lookupField = field as SPFieldLookup;
var lookupList = list.ParentWeb.Lists[Guid.Parse(lookupField.LookupList)];
var query = new SPQuery();
query.Query = String.Format("<OrderBy><FieldRef Name='{0}'/></OrderBy>", lookupField.LookupField);
foreach (SPListItem item in lookupList.GetItems(query))
{
results.Add(new SPFieldLookupValue(item.ID, item[lookupField.LookupField].ToString()));
}
return results;
}
Then to use it, your code would look something like this:
var list = SPContext.Current.Web.Lists["My List"];
var results = GetLookupFieldValues(list, "Actual City");
foreach (SPFieldLookupValue result in results)
{
var value = result.LookupValue;
var id = result.LookupId;
}
I think there is no explicit method returning what you want. But the SPFieldLookup class stores all the info you need to request this information manually: LookupField and LookupList
So you could retrieve the information by getting it form the list you lookup field uses. To make it reusable you could implement it as a Extension Method. So the next time you could really call f.GetAllPossibleValues();.
As I understand you want to query all values that are in use?
If so, you would have to query items where Actual City is not null, query would look something like:
<Where><IsNotNull><FieldRef Name='Actual City'/></IsNotNull></Where>
Then, for each queried item you would
List<SPFieldLookupValue> result = new List<SPFieldLookupValue>(returnedItemCount * 5);
foreach (SPListItem item in queriedItems) {
object lookup = item["Actual City"];
SPFieldLookupValueCollection lookupValues = new SPFIeldLookupValueCollection(
(lookup != null) ? lookup.ToString() : ""
);
foreach (SPFieldLookupValue lookupValue in lookupValues) {
if (!result.Contains(lookupValue)) {
result.Add(lookupValue);
}
}
}
Or you could use HashTable where LookupId would be string and LookupValue would be int id and then check if HashTable.ContainsKey(lookupId)... must be faster to find an integer in hashtable rather than string in list, but the resource intensive part is to probably query all items where that field contains some value and then loop...
If you want to enumerate all possible values, that means you basically want to get all the Title field values from all the items in the Cities list. I don't think there is a method like GetAllPossibleValues() in SharePoint, but you can either just list all the items in Cities and get their titles, if there's just a few, or use a CAML query if there's plenty.

Read/write Person metadata from a Word doc stored in SharePoint using VBA or VSTO?

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;

Resources