Wednesday, May 13, 2009

SPListItem will not update

Not even close to a record – second “easy thing that eats up a few hours”.

The situation: Simple postback event handler that updates a field in a list to a new value. Here is the code:

protected void DenyRequest( object sender, EventArgs e )
{
    try
    {
        Item[fieldname] = RequestStatus.Denied;
                
        Item.Update();
        RedirectToPreviousPage();
    }
    catch (Exception ex)
    {
        errorLabel.Text = string.Format("Sorry, there was an unexpected error: {0}", ex.Message);
    }
}


The issue: The field value never changes! The line of code gives no indication of failure – the update also succeeds – but the value never freakin changed.



The solution I found to by way of this dude’s blog: Nick Grattan Blog Post who needed to get a new reference to the item to have it change the value. So the working code looks like this:



protected void DenyRequest( object sender, EventArgs e )
{
    try
    {
        SPListItem item = List.GetItemById(Convert.ToInt32(ItemID));
        item[fieldname] = RequestStatus.Denied;
        item.Update();
        RedirectToPreviousPage();
    }
    catch (Exception ex)
    {
        errorLabel.Text = string.Format("Sorry, there was an unexpected error: {0}", ex.Message);
    }
}


So the difference was that before the Item was a property that returned the list item using the GetItemById method using the same ItemID property, and now that is done inline with the update code. Is it just me, or should the code work either way? What is the difference if you have a property that returns the item or get the item inline with the update?!



Oh, SharePoint Object Model, you’ve done it again!

No comments:

Post a Comment

 
© I caught you a delicious bass.
Back to top