Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
228 views
in Technique[技术] by (71.8m points)

c# - Update Sharepoint List Item

I got following error...

System.NullReferenceException: Object reference not set to an instance of an object. at Microsoft.SharePoint.SPListItem.get_UniqueId() at ConsoleApplication1.Program.Main(String[] args) in Program.cs:line 21

running following code

using (SPSite site = new SPSite("http://site/"))
{    
    using (SPWeb web = site.OpenWeb())
    {
        try
        {
            SPList list = web.Lists["ListName"]; // 2        
            SPListItem item = list.Items.Add();
            Guid itemId = item.UniqueId;
            SPListItem itemUpdate = web.Lists["ListName"].Items[itemId];
            itemUpdate["PercentComplete"] = .45; // 45%        
            itemUpdate.Update();
        }
        catch (Exception e)
        { 
            Console.WriteLine(e);
            Console.ReadLine();

        }
    }
}

What's the problem?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

If you're trying to alter values for a just inserted list item, you should go with:

SPList list = web.Lists["ListName"];
//SPListItem item = list.Items.Add();
//item["PercentComplete"] = .45; // 45%
//item.Update();

SPListItemCollection items = list.GetItems(new SPQuery()
{
    Query = @"<Where>
                <Eq>
                   <FieldRef Name='Title' />
                   <Value Type='Text'>Desigining</Value>
                </Eq>
              </Where>"
});

foreach (SPListItem item in items)
{
    item["PercentComplete"] = .45; // 45%
    item.Update();
}

You just need to use list.Items[uniqueId] or faster list.GetItemByUniqueId(uniqueId) if you needs to find a particular item to update; what can be accomplished by using SPQuery class.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...