Updating a SharePoint List Item.
This post started after trying to solve an issue for a SharePoint Developer regarding Lookup columns for SharePoint. I started to test the same code in the Microsoft Virtual Labs and trying to solve the issue turned out to be a useful learning experience for me. Updating a list item seemed much simpler. I first created the "Sample1" Parent list containing the values
1. Approved
2. Pending
Then I created a second list "Sample2" list and added the custom Lookup column from the "Sample1" list.
Then, while testing in Powershell, the new columns are not appearing. Magically after sometime, the new columns are showing up. I believe this may be due to longer time for updated list to appear in Powershell. I realised my mistake.
The following script in Powershell does not show the expected new columns immediately.
(Get-SpWEb -identity "http://w15-sp").Lists["Sample2"].Items[1] |select Title,Status --WRONG
Get-SpWEb -identity "http://w15-sp").Lists["Sample2"].Items[1]["Status"]
The custom fields are stored in the "XML" COLUMNS and cannot be viewed as you see in the Browser of a SharePoint site.
Below is a code to update lookup column in SharePoint site
|
Add-PSSnapin
"Microsoft.SharePoint.Powershell"
$wpSite
= Get-SPWeb "http://w15-sp"
$secondListItem
= $wpSite.Lists["Sample2"].Items[1]
$secondListItem["Status"]
= "1;#Approved"
$secondListItem.Update();
$secondListItem["Status"]
|
I tested the same updation using C#
|
using (SPSite wpSite = new SPSite("http://w15-sp"))
{
SPWeb wpWeb =
wpSite.OpenWeb();
//Get list
"Sample1" with LookUp values 1:Approved;2:Rejected
SPList
lstSample1 = wpWeb.Lists["Sample1"];
//Actual list
to be updated
SPList
lstSample2 = wpWeb.Lists["Sample2"];
SPListItem
secondItem = lstSample2.Items[1];
Console.WriteLine("Old values {0} {1}",
secondItem["Title"], secondItem["Status"]);
SPFieldLookupValue newValue = new SPFieldLookupValue(2,
"Rejected");
secondItem["Status"] = newValue;
secondItem.Update();
//After Update
Console.WriteLine("New values {0} {1}",
secondItem["Title"], secondItem["Status"]);
Console.ReadLine();
}
|