How to add a value to a lookup field in sharepoint? - c#

Hi I have two Lists in sharepoint 2007.
I have a lookup column in on list which looks the other field.
I want to use the sharepoint object model to add an item to the second list.
How to i set the lookup field value. (The value is already in the other list).?
SPListItem Employee = web.Lists["Employee"].Items.Add();
Employee["Name"] = account.Name;
Employee["Department"] = <lookup value must come here>
Employee.Update();

Lookup fields will contain a combination of the row's id and the value of the column to display, separated by :#, in your case that could be 1:#HumanResources or 12:#Engineering.
So to reference a lookup simply setting the id won't be enough, instead the above mentioned string needs to be set. Luckily SharePoint provides the class SPFieldLookupValue that does exactly this:
var department = web.Lists["Department"].GetItemById(1);
var employee = web.Lists["Employee"].Items.Add();
employee["Name"] = account.Name;
employee["Department"] = new SPFieldLookupValue(department.ID, department.Title);
employee.Update();

Related

Field Not Recognized on AddAsync of SharePoint List Item

When I try to create a new list item with the basic calendar/list fields everything works perfectly. However, when I try to do so with a "non-standard" field i.e. a field I added, I am getting a "field not recognized" error.
The field is clearly there! Is there some special way I need to populate these custom fields?
// get a specific list
ISiteListsCollectionPage list = await graphClient.Sites["root"].Lists.Request()
.Filter($"DisplayName eq 'Outlook Integration'").GetAsync();
// create a dictionary of [calendar] list properties
Dictionary<string, object> props = new Dictionary<string, object>();
// populate properties, all of these work just fine
props.Add("Title", evt.Subject);
props.Add("Location", evt.Location?.DisplayName);
props.Add("EventDate", utcStart.ToString("yyyy-MM-ddTHH:mm:ssK"));
props.Add("EndDate", utcEnd.ToString("yyyy-MM-ddTHH:mm:ssK"));
props.Add("Description", Regex.Replace(evt.Body.Content, "<.*?>", String.Empty)); // remove HTML content
// populate custom properties
props.Add("ResourceID", evt.Id); // throws error: Field 'ResourceID' is not recognized
// create list item with our properties dictionary
var newItem = new ListItem
{
Name = "My New Event",
Fields = new FieldValueSet()
{
AdditionalData = props
}
};
// call the service and get the result
var newListItem = await graphClient.Sites["root"].Lists[list[0].Id].Items.Request().AddAsync(newItem);
This is the complete list of fields on my list:
Here you can see the display name is "ResourceID" whereas the API name is "O365EventId." However, both result in the same error, "Field not recognized."
Note: ResourceID is one of the fields that I added. How can I set the value of this field via the Graph API?
Marc is right by saying in comment regarding column name, the provided screenshot displays Column.displayName which is
The user-facing name of the column.
but what actually FieldValueSet.AdditionalData expects as a key is Column.name which is:
The API-facing name of the column as it appears in the fields on a
listItem. For the user-facing name, see displayName.
In your case most likely displayName and name properties are different, you could verify it via following endpoint:
https://graph.microsoft.com/v1.0/sites/root/lists/Outlook Integration/columns
and that's the reason why this error occurs.
Via the Graph API client (C#), you can see a list of all columns for any given list like so:
// get specific list by name
ISiteListsCollectionPage list = await graphClient.Sites["root"].Lists.Request()
.Filter($"DisplayName eq 'YOUR_LIST_NAME_HERE'").GetAsync();
// get columns and output them to the log as a serialized object
var listColumns = await graphClient.Sites["root"].Lists[list[0].Id].Columns.Request().GetAsync();
logger.LogInformation($"List Columns Object: {JsonConvert.SerializeObject(listColumns).ToString()}");

Lookup column in SharePoint Task List of a Visual Studio Workflow

I have a State Machine SharePoint 2010 Workflow. The task is created by content type. I wanted to add a lookup column in task list. I was able to successfully add values to other custom field into the task list but having problem when I try add values to the lookup column of the task list.
Following code snippets were from CreateApproverTaskWithCT method.
//**I amable to add values to custom columns like this
createApproverTaskWithCT_TaskProperties1.ExtendedProperties[GetField("StatusReview")] = "Pending";
//**I am not able to add values to lookup column
createApproverTaskWithCT_TaskProperties1.ExtendedProperties[GetField("AgencyNameLookup")] = new SPFieldLookupValue(agencyItem.ID, agencyItem["Agency Legal Name"].ToString());
where agencyItem is a SPListItem for the corresponding lookup column.
and GetField method return the guid of the custom field.
private Guid GetField(string field_name)
{
Guid statusFieldId = workflowProperties.TaskList.Fields.GetFieldByInternalName(field_name).Id;
return statusFieldId;
}
Any suggestions would be highly appreciated.
I was able to insert values to look up field in task list by following method:
createApproverTaskWithCT_TaskProperties1.ExtendedProperties[GetField("AgencyNameLookup")] = String.Format(agencyItem.ID + ";#" + agencyItem["Agency Legal Name"].ToString());

Programmatically Add Dependent External Lookup Field to SPView in SharePoint 2010

I have been able to programmatically add external (i.e. BDC) lookup fields to a list and I have also been able to add dependent external lookup fields to the same list. What I have not been able to figure out is how to programmatically add the dependent external lookup fields to the list's default view.
This article on MSDN gives an example of how to add a regular dependent lookup field to an SPView -but I have yet to find an example that shows how to programmatically add a dependent external lookup field to an SPView.
Below is the code in the FeatureActivated method of my EventReceiver that I am using to add the dependent external lookup fields to my SharePoint list and my attempt at adding the field to the list's default view.
var web = ((SPSite)properties.Feature.Parent).RootWeb;
var list = web.Lists.TryGetList("MyList");
var fldName = "EmployeeID";
var fld = list.Fields.CreateNewField("BusinessData", fldName) as SPBusinessDataField;
fld.SystemInstanceName = lobSystemInstanceName;
fld.EntityNamespace = entityNamespace;
fld.EntityName = entityName;
fld.BdcFieldName = entityFieldName;
//The dictionary object defined below contains key/value pairs that represent the
//field name as a string along with a boolean flag that specifies whether or not
//the secondary field should be added to the default view.
var secondaryFieldNames = new Dictionary<string, bool>()
{
{"FirstName", true},
{"LastName", true},
{"Title", false}
}
fld.SetSecondaryFieldsNames(secondaryFieldNames.Select(e => e.Key).ToArray());
var view = list.Views.DefaultView;
foreach (var secFld in secondaryFieldNames)
{
var viewFieldName = String.Format("{0}: {1}", fldName, secFld.Key);
if (!view.ViewFields.Exists(viewFieldName) && secFld.Value)
{
view.ViewFields.Add(viewFieldName);
view.Update();
}
}
As mentioned previously, the primary lookup field and all secondary lookup fields are successfully added to the list. The primary lookup field is successfully added to the list's default view. The seconday fields are not.
Storing the viewfield collection in a variable did the trick for me (don't really know why).
foreach (var secFld in secondaryFieldNames)
{
var viewFieldName = String.Format("{0}: {1}", fldName, secFld.Key);
var viewFields = view.ViewFields;
if (!viewFields.Exists(viewFieldName) && secFld.Value)
{
viewFields.Add(viewFieldName);
view.Update();
}
}

LINQ - Accessing a column with the column name as a string parameter

(Similar to this question)
I have tables called 'Questions' and 'FinalFigures':
Questions (QuestionID, Text, FinalFiguresColumnName)
FinalFigures (FinalFigureID, TotalDays, TotalCost, etc, etc)
'FinalFiguresColumnName' would have values like "TotalDays", "TotalCost", etc. Is there a simple way to loop through a set of Questions and have the 'Text' value saved to the corresponding column name on the 'FinalFigures' table?
Ie. instead of:
var item = new FinalFigure();
item.TotalDays = "x";
I need:
var item = new FinalFigure();
// access the column 'TotalDays' with its name as a string, not a property
You can use a bit of reflection to get the property value by the string name of the property instead of directly accessing it.
var value = (int)item.GetType().GetProperty("TotalDays").GetValue(item);
To set the value, simply call SetValue();
item.GetType().GetProperty("TotalDays").SetValue(item, value);

Updating a field on list items based on the value selected from drop down "choice" column

I have the following problem I have two list "TestUsers" amd "TestGroups". The "TestUsers" list has two columns [Group - Choice], [User - Single line of text]. The "TestGroups" list has two columns [Group - Single line of text], [CheckedOut - Single line of text].
The data in both lists are the following:
TestUsers (List):
User: testuser1
Group: groupA
User: testuser2
Group: groupB
TestGroups (List):
Group: groupA
CheckedOut: testuser1
The requirement is that when a user in the "TestUsers" lists gets its "Group" changed for example from "groupA" to "groupB" than this should also be reflected and automatically updated in the "TestGroups" list. So for example in the "TestUsers" list if I were to change the "Group" for "testuser1" to "groupB" then in the "TestGroups" list the "Group" of "testuser1" has to also change/update to "groupB".
I hope the above is clear enough in describing what the requirement is.
I have tried doing this using worklflows and having lookup column as well as calculated columns. But both the calculated columns and the lookup columns does not seem to be work.
How would I go about achieving this using code in c#. I know how to update list items but what I am not sure is how to update listitems from a list when a value is changed on a separate list as mentioned earlier.
I am stuck with this issue and thought I post it here so I can get some quick and accurate suggestions on how to procceed.
Many thanks, any help with this will be greatly appreciated.
you can try this In event receiver use ItemUpdating Event method just check it out item changed or not and create your logic
public override void ItemUpdating(SPItemEventProperties properties)
{
base.ItemUpdated(properties);
if (properties.ListTitle == "TestUsers")
{
SPWeb web = properties.OpenWeb();
SPList list = web.Lists[properties.ListTitle];
SPListItem litemUser = list.GetItemById(properties.ListItemId);
SPList objFeatureList = web.Lists["TestGroups"];
SPQuery objParentQuery = new SPQuery();
string user = properties.AfterProperties["User"].ToString();
//in Caml query just find it out listitem which contain Users and than update its listitem.
objParentQuery.Query = "<Where><Eq><FieldRef Name='Check_x0020_it_x0020_out'/><Value Type='Integer'>"+You should set Userid in Field From litemUser +"</Value></Eq></Where>";
SPListItemCollection liitemcol = objFeatureList.GetItems(objParentQuery);
foreach (SPListItem litemGroup in liitemcol)
{
litemGroup["Group"] = litemUser["Group"];
litemGroup.Update();
// or if you want to using Workflow just startWorflow when item has match over here.
}
}
}

Categories