Logo 
Search:

Sharepoint Forum

Ask Question   UnAnswered
Home » Forum » Sharepoint       RSS Feeds

Using SPListItem's .Update() to update one field based on another

  Asked By: Geoffrey    Date: Dec 10    Category: Sharepoint    Views: 5456

I created a "mass approvals" view to allow users to check off
checkboxes on multiple number of documents in the doc library. I then
coded the back end to update another column in the list if the
checkbox is checked off. I'm having problems updating the checkbox,
and also updating the column value based on the checkbox.

In the datasheet view. Even though I checked off the box to "allow
users to edit this column in a datasheet view" when I promote the
fields in InfoPath, in the datasheet view the column is set to "read
only".

In the code, the field (User Approval) doesn't seem to allow me to
update it either. Here is the code:
TheListItem["User Approval"] = "Approved";
//Here I check to make sure it is equal to Approved and it is:
Console.WriteLine(TheListItem["User Approval"].ToString());
Console.ReadKey(true);
//Here I update the req:
Req.Update();
//Here I check if the code worked, and it didn't - it's back to the
original value of "Pending":
Console.WriteLine(TheListItem["User Approval"].ToString());
Console.ReadKey(true);

Do you think I need to use SPField instead of SPListItem to update
the field?

Share: 

 

8 Answers Found

 
Answer #1    Answered By: Luke Davis     Answered On: Dec 10

I have the code  done, but it is not updating  the field. Any idea why
the before and after values of "COO Approval" are not agreeing?

SPList oList = Site.Lists["Purchasing Requisitions"];
string requistionsURL = ConfigurationManager.AppSettings
["Requisitions"];
SPQuery query = new SPQuery();
System.Text.StringBuilder oSb = new System.Text.StringBuilder();
oSb.Append("<Where>");
oSb.Append(" <Geq>");
oSb.Append(" <FieldRef Name='Modified' />");
oSb.Append(" <Value Type=\"+DateTime\"><Today
OffsetDays=\"-2\" /></Value>");
oSb.Append(" </Geq>");
oSb.Append("</Where>");
query.Query = oSb.ToString();
SPListItemCollection Reqs = oList.GetItems(query);
int ReqCount = Reqs.Count;
for (int k = 0; k < ReqCount; k++)
{ //Loop thru to a modified Requisition form
SPListItem Req = Reqs[k];
string doclocation = "http://SPServer/Requisitions/" + Req.Name + "?
noredirect=true";
Console.WriteLine("req# " + k.ToString() + "=" + Req.Name);
SPFieldUrlValue linkUrl = new SPFieldUrlValue();
linkUrl.Url = doclocation;
WebRequest request = WebRequest.Create(linkUrl.Url);
request.Credentials = CredentialCache.DefaultCredentials;
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
Stream dataStream = response.GetResponseStream();
StreamReader reader = new StreamReader(dataStream);
string responseFromServer = reader.ReadToEnd();
//PARSE XML
string xmlDoc1 = responseFromServer.Replace("my:", "").ToString();
XmlDocument xmlDocument = new XmlDocument();
xmlDocument.LoadXml(xmlDoc1);
string requisitionNumber = xmlDocument.SelectSingleNode
(".//RequisitionNumber").InnerText.Replace(":", "_");
string COOApproval = Req["COO Approval"].ToString();
//UPDATE REQUISITION FIELD:
if ( (COOApproval == "Pending") && (Req["COO Mass
Approved"].ToString() == "True") )
{
//UPDATE COO Approval FIELD:
SPListItem ReqUpdate = Reqs[k];
ReqUpdate["COO Approval"] = "Approved";
//BEFORE:
Console.WriteLine("reqItem[COO Approval]=" + ReqUpdate["COO
Approval"].ToString());
Console.ReadKey(true);
ReqUpdate.Update();
//AFTER:
Console.WriteLine("reqItem[COO Approval]=" + ReqUpdate["COO
Approval"].ToString());
Console.ReadKey(true);
}
}

 
Answer #2    Answered By: Daniella Landry     Answered On: Dec 10

Looks like you're pulling the items out into a separate SPListItemCollection
(which is better than looping, for performance reasons), and then creating
another new SPListItem from that collection, at which point you change the
value. You need to change the field  value in the original instance of the
item, from the original list.

If necessary, get the ID of the item and then use GetItemByID (that might
not be the exact method name) to pull the SPListItem from the list  and
update accordingly.

 
Answer #3    Answered By: Bo Stafford     Answered On: Dec 10

Here is the latest code  with suggestions I received but I get the
same problem - it does not update  the COO Approval field. Does
anyone have any idea whether I need to use SPException in my "catch"
section? The code as it stands does not return an error. Any other
ideas would be appreciated!

namespace MassApprovals
{
class Program
{
static void Main(string[] args)
{
SPSite SiteCollection1 = new SPSite
("http://SPServer/PurchasingSite/");
SPWeb Web = SiteCollection1.OpenWeb();
SPSecurity.RunWithElevatedPrivileges(delegate()
{
SPSite SiteCollection = new SPSite
(SiteCollection1.ID);
SPWeb Site = SiteCollection.OpenWeb(Web.ID);
SiteCollection.AllowUnsafeUpdates = true;
Site.AllowUnsafeUpdates = true;
try
{
SPList oList = Site.Lists["Requisitions"];
string requistionsURL =
ConfigurationManager.AppSettings["Requisitions"];
SPQuery query = new SPQuery();
System.Text.StringBuilder oSb = new
System.Text.StringBuilder();
oSb.Append("<Where>");
oSb.Append(" <Geq>");
oSb.Append(" <FieldRef
Name='Modified' />");
oSb.Append(" <Value
Type=\"+DateTime\"><Today OffsetDays=\"-1\" /></Value>"); //format:
2009-02-17
oSb.Append(" </Value>");
oSb.Append(" </Geq>");
oSb.Append(" <Eq>");
oSb.Append(" <FieldRef
Name='Status' />");
oSb.Append(" <Value Type='Text'>In
Process");
oSb.Append(" </Value>");
oSb.Append(" </Eq>");
oSb.Append("</Where>");
query.Query = oSb.ToString();
SPListItemCollection Reqs = oList.GetItems(query);
int ReqCount = Reqs.Count;
if (dbg) { Console.WriteLine("ReqCount: " +
ReqCount.ToString()); } //Console.ReadKey(true); }
for (int k = 0; k < ReqCount; k++) //1454
{
SPListItem Req = Reqs[k];
string doclocation
= "http://SPServer/Purchasing/Requisitions/" + Req.Name + "?
noredirect=true";
SPFieldUrlValue linkUrl = new SPFieldUrlValue
();
linkUrl.Url = doclocation;
WebRequest request = WebRequest.Create
(linkUrl.Url);
request.Credentials =
CredentialCache.DefaultCredentials;
HttpWebResponse response = (HttpWebResponse)
request.GetResponse();
Stream dataStream = response.GetResponseStream
();
StreamReader reader = new StreamReader
(dataStream);
string responseFromServer = reader.ReadToEnd
();
string xmlDoc1 = responseFromServer.Replace
("my:", "").ToString();
XmlDocument xmlDocument = new XmlDocument();
xmlDocument.LoadXml(xmlDoc1);
if (dbg) { Console.WriteLine("Checking: " +
Req.Name); }
if (Req["COO Mass Approved"] == null)
{ }
else
{
if ((Req["COO Approval"].ToString()
== "Pending") &&
(Req["COO Mass Approved"].ToString
() == "True") //&& (requisitionNumber == "dmorrissey2009-02-
06T11_10_12")
)
{ //UPDATE REQUISITION FIELDS:
Req.Web.AllowUnsafeUpdates = true;
Req.BreakRoleInheritance(true);
Req.Web.AllowUnsafeUpdates = true;
Req["COO Approval"] = "Approved";
//if (dbg) { Console.WriteLine
("reqItem[COO Approval] before update=" + Req["COO Approval"].ToString
()); Console.ReadKey(true); }
Req.SystemUpdate(false);
if (dbg) { Console.WriteLine("reqItem
[COO Approval] after update=" + Req["COO Approval"].ToString());
Console.ReadKey(true); }
}
}
}
Console.Write("Done");
Console.ReadKey(true);
}
catch (Exception ex)
{
Console.Write(ex.Message);
Console.ReadKey(true);

return;
}
});
}
}
}

 
Answer #4    Answered By: Jocelyn Shelton     Answered On: Dec 10

It appears that you're still making the change to the separate
ListItemCollection object, rather than to the original list  item itself.

 
Answer #5    Answered By: Joey Soto     Answered On: Dec 10

Are you saying I should resturcutre the code  to update  oList, not Req
or Reqs[k]?

 
Answer #6    Answered By: Gerard Randall     Answered On: Dec 10

Exactly. I believe you're updating  a separate instance of the item, rather
than a pointer to the item itself.

 
Answer #7    Answered By: Audra Mccormick     Answered On: Dec 10

There is an excellent opensource utility on Microsoft's CodePlex site
called "SharePoint Manager 2007". I just downloaded it at
http://www.codeplex.com/spm to our SP server. It runs immediately
and you can drill down to the listitem guid level, get internal
names - "anything in stsadm.exe and more". Has anyone else used this
tool?

 
Answer #8    Answered By: Christina Lewis     Answered On: Dec 10

Do you have any suggestions if there is any other setting that would
prohibit me from updating  the Approval field  through code  or
workflow? Is there a setting I am missing?\

This is the latest code that I have updated per recent suggestions.
I've included the various "TEST ASSIGNMENTS" and "TEST UPDATES" I've
tried:

namespace MassApprovals
{
class Program
{
static void Main(string[] args)
{
SPSecurity.RunWithElevatedPrivileges(delegate()
{
SPSite SiteCollection = new SPSite
("http://SPServer/AcctDept/Purchasing/");
SPWeb Web = SiteCollection.OpenWeb();
SiteCollection.AllowUnsafeUpdates = true;
Web.AllowUnsafeUpdates = true;
string Approved = "Approved";
try
{
SPList oList = Web.Lists["Purchasing
Requisitions"];
string requistionsURL =
ConfigurationManager.AppSettings["Requisitions"];
SPQuery query = new SPQuery();
System.Text.StringBuilder oSb = new
System.Text.StringBuilder();
oSb.Append("<Where>");
oSb.Append(" <And>");
oSb.Append(" <Eq>");
oSb.Append(" <FieldRef
Name='Status' />");
oSb.Append(" <Value Type='Choice'>In
Process</Value>");
oSb.Append(" </Eq>");
oSb.Append(" <Eq>");
oSb.Append(" <FieldRef
Name='_x0037_62650b3_x002d_d029_x002d_4c38_x002d_a591_x002d_1554223473
6b' />"); //(Include all where COO's Approval is pending)
oSb.Append(" <Value
Type='Text'>Pending</Value>");
oSb.Append(" </Eq>");
oSb.Append(" </And>");
oSb.Append("</Where>");
query.Query = oSb.ToString();

SPListItemCollection Reqs = oList.GetItems(query);

Guid COOApproval = new Guid("762650b3-d029-4c38-
a591-15976234536b"); //Field GUID of "COOApproval"
int ReqCount = Reqs.Count;
if (dbg) { Console.WriteLine("ReqCount: " +
ReqCount.ToString()); }
Guid ReqGUID = new Guid();

for (int k = 0; k < ReqCount; k++)
{
Console.WriteLine("--------------Req Being
Analyzed:------------");
Console.WriteLine("req# " + k.ToString() + ";
Reqs[k].Name = " + Reqs[k].Name.ToString());

if (Reqs[k]["COO Mass Approved"] == null)
{ }
else
{
if ((Reqs[k]["COO Approval"].ToString()
== "Pending") &&
(Reqs[k]["COO Mass
Approved"].ToString() == "True")
)
{
//UPDATE REQUISITION FIELDS:
ReqGUID = Reqs[k].UniqueId;
oList.GetItemByUniqueId(ReqGUID);

SPListItem Req = oList.Items[ReqGUID];
int ReqID = oList.Items
[ReqGUID].ID; //Reqs[k].ID;

try
{
//TEST ASSIGNMENTS: I've tried
assigning the new value three different ways:
Req[COOApproval] = Approved;
Reqs[ReqGUID][COOApproval] =
Approved;
oList.Items[ReqGUID][COOApproval]
= Approved;
//TEST UPDATES: I've tried
updating several different ways:
Req.SystemUpdate(false);
Reqs
[ReqGUID].Web.AllowUnsafeUpdates = true;
Reqs
[ReqGUID].UpdateOverwriteVersion();
oList.Update();
oList.Items
[ReqGUID].UpdateOverwriteVersion();
}
catch (SPException ex)
{
Console.Write(ex.Message);
Console.ReadKey(true);

return;
}
catch (Exception ex)
{
Console.Write(ex.Message);
Console.ReadKey(true);

return;
}
}
}
}
Console.Write("Done");
Console.ReadKey(true);
});

}
}

}

 




Tagged: